home *** CD-ROM | disk | FTP | other *** search
/ Amiga Format CD 7 / Amiga Format AFCD07 (Dec 1996, Issue 91).iso / serious / shareware / programming / emacs-complete / fsf / emacs / lisp / files.el < prev    next >
Lisp/Scheme  |  1994-08-27  |  88KB  |  2,233 lines

  1. ;;; files.el --- file input and output commands for Emacs
  2.  
  3. ;; Copyright (C) 1985, 86, 87, 92, 93, 94 Free Software Foundation, Inc.
  4.  
  5. ;; Maintainer: FSF
  6.  
  7. ;; This file is part of GNU Emacs.
  8.  
  9. ;; GNU Emacs is free software; you can redistribute it and/or modify
  10. ;; it under the terms of the GNU General Public License as published by
  11. ;; the Free Software Foundation; either version 2, or (at your option)
  12. ;; any later version.
  13.  
  14. ;; GNU Emacs is distributed in the hope that it will be useful,
  15. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  17. ;; GNU General Public License for more details.
  18.  
  19. ;; You should have received a copy of the GNU General Public License
  20. ;; along with GNU Emacs; see the file COPYING.  If not, write to
  21. ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
  22.  
  23. ;;; Commentary:
  24.  
  25. ;; Defines most of Emacs's file- and directory-handling functions,
  26. ;; including basic file visiting, backup generation, link handling,
  27. ;; ITS-id version control, load- and write-hook handling, and the like.
  28.  
  29. ;;; Code:
  30.  
  31. (defconst delete-auto-save-files t
  32.   "*Non-nil means delete auto-save file when a buffer is saved or killed.")
  33.  
  34. (defconst directory-abbrev-alist
  35.   nil
  36.   "*Alist of abbreviations for file directories.
  37. A list of elements of the form (FROM . TO), each meaning to replace
  38. FROM with TO when it appears in a directory name.  This replacement is
  39. done when setting up the default directory of a newly visited file.
  40. *Every* FROM string should start with `^'.
  41.  
  42. Do not use `~' in the TO strings.
  43. They should be ordinary absolute directory names.
  44.  
  45. Use this feature when you have directories which you normally refer to
  46. via absolute symbolic links.  Make TO the name of the link, and FROM
  47. the name it is linked to.")
  48.  
  49. ;;; Turn off backup files on VMS since it has version numbers.
  50. (defconst make-backup-files (not (eq system-type 'vax-vms))
  51.   "*Non-nil means make a backup of a file the first time it is saved.
  52. This can be done by renaming the file or by copying.
  53.  
  54. Renaming means that Emacs renames the existing file so that it is a
  55. backup file, then writes the buffer into a new file.  Any other names
  56. that the old file had will now refer to the backup file.  The new file
  57. is owned by you and its group is defaulted.
  58.  
  59. Copying means that Emacs copies the existing file into the backup
  60. file, then writes the buffer on top of the existing file.  Any other
  61. names that the old file had will now refer to the new (edited) file.
  62. The file's owner and group are unchanged.
  63.  
  64. The choice of renaming or copying is controlled by the variables
  65. `backup-by-copying', `backup-by-copying-when-linked' and
  66. `backup-by-copying-when-mismatch'.  See also `backup-inhibited'.")
  67.  
  68. ;; Do this so that local variables based on the file name
  69. ;; are not overridden by the major mode.
  70. (defvar backup-inhibited nil
  71.   "Non-nil means don't make a backup, regardless of the other parameters.
  72. This variable is intended for use by making it local to a buffer.
  73. But it is local only if you make it local.")
  74. (put 'backup-inhibited 'permanent-local t)
  75.  
  76. (defconst backup-by-copying nil
  77.  "*Non-nil means always use copying to create backup files.
  78. See documentation of variable `make-backup-files'.")
  79.  
  80. (defconst backup-by-copying-when-linked nil
  81.  "*Non-nil means use copying to create backups for files with multiple names.
  82. This causes the alternate names to refer to the latest version as edited.
  83. This variable is relevant only if `backup-by-copying' is nil.")
  84.  
  85. (defconst backup-by-copying-when-mismatch nil
  86.   "*Non-nil means create backups by copying if this preserves owner or group.
  87. Renaming may still be used (subject to control of other variables)
  88. when it would not result in changing the owner or group of the file;
  89. that is, for files which are owned by you and whose group matches
  90. the default for a new file created there by you.
  91. This variable is relevant only if `backup-by-copying' is nil.")
  92.  
  93. (defvar backup-enable-predicate
  94.   '(lambda (name)
  95.      (or (< (length name) 5)
  96.      (not (string-equal "/tmp/" (substring name 0 5)))))
  97.   "Predicate that looks at a file name and decides whether to make backups.
  98. Called with an absolute file name as argument, it returns t to enable backup.")
  99.  
  100. (defconst buffer-offer-save nil
  101.   "*Non-nil in a buffer means offer to save the buffer on exit
  102. even if the buffer is not visiting a file.
  103. Automatically local in all buffers.")
  104. (make-variable-buffer-local 'buffer-offer-save)
  105.  
  106. (defconst find-file-existing-other-name nil
  107.   "*Non-nil means find a file under alternative names, in existing buffers.
  108. This means if any existing buffer is visiting the file you want
  109. under another name, you get the existing buffer instead of a new buffer.")
  110.  
  111. (defconst find-file-visit-truename nil
  112.   "*Non-nil means visit a file under its truename.
  113. The truename of a file is found by chasing all links
  114. both at the file level and at the levels of the containing directories.")
  115.  
  116. (defvar buffer-file-truename nil
  117.   "The abbreviated truename of the file visited in the current buffer.
  118. That is, (abbreviated-file-name (file-truename buffer-file-name)).
  119. This variable is automatically local in all buffers, when non-nil.")
  120. (make-variable-buffer-local 'buffer-file-truename)
  121. (put 'buffer-file-truename 'permanent-local t)
  122.  
  123. (defvar buffer-file-number nil
  124.   "The device number and file number of the file visited in the current buffer.
  125. The value is a list of the form (FILENUM DEVNUM).
  126. This pair of numbers uniquely identifies the file.
  127. If the buffer is visiting a new file, the value is nil.")
  128. (make-variable-buffer-local 'buffer-file-number)
  129. (put 'buffer-file-number 'permanent-local t)
  130.  
  131. (defconst file-precious-flag nil
  132.   "*Non-nil means protect against I/O errors while saving files.
  133. Some modes set this non-nil in particular buffers.")
  134.  
  135. (defvar version-control nil
  136.   "*Control use of version numbers for backup files.
  137. t means make numeric backup versions unconditionally.
  138. nil means make them for files that have some already.
  139. `never' means do not make them.")
  140.  
  141. (defvar dired-kept-versions 2
  142.   "*When cleaning directory, number of versions to keep.")
  143.  
  144. (defvar delete-old-versions nil
  145.   "*If t, delete excess backup versions silently.
  146. If nil, ask confirmation.  Any other value prevents any trimming.")
  147.  
  148. (defvar kept-old-versions 2
  149.   "*Number of oldest versions to keep when a new numbered backup is made.")
  150.  
  151. (defvar kept-new-versions 2
  152.   "*Number of newest versions to keep when a new numbered backup is made.
  153. Includes the new backup.  Must be > 0")
  154.  
  155. (defconst require-final-newline nil
  156.   "*Value of t says silently ensure a file ends in a newline when it is saved.
  157. Non-nil but not t says ask user whether to add a newline when there isn't one.
  158. nil means don't add newlines.")
  159.  
  160. (defconst auto-save-default t
  161.   "*Non-nil says by default do auto-saving of every file-visiting buffer.")
  162.  
  163. (defconst auto-save-visited-file-name nil
  164.   "*Non-nil says auto-save a buffer in the file it is visiting, when practical.
  165. Normally auto-save files are written under other names.")
  166.  
  167. (defconst save-abbrevs nil
  168.   "*Non-nil means save word abbrevs too when files are saved.
  169. Loading an abbrev file sets this to t.")
  170.  
  171. (defconst find-file-run-dired t
  172.   "*Non-nil says run dired if `find-file' is given the name of a directory.")
  173.  
  174. ;;;It is not useful to make this a local variable.
  175. ;;;(put 'find-file-not-found-hooks 'permanent-local t)
  176. (defvar find-file-not-found-hooks nil
  177.   "List of functions to be called for `find-file' on nonexistent file.
  178. These functions are called as soon as the error is detected.
  179. `buffer-file-name' is already set up.
  180. The functions are called in the order given until one of them returns non-nil.")
  181.  
  182. ;;;It is not useful to make this a local variable.
  183. ;;;(put 'find-file-hooks 'permanent-local t)
  184. (defvar find-file-hooks nil
  185.   "List of functions to be called after a buffer is loaded from a file.
  186. The buffer's local variables (if any) will have been processed before the
  187. functions are called.")
  188.  
  189. (defvar write-file-hooks nil
  190.   "List of functions to be called before writing out a buffer to a file.
  191. If one of them returns non-nil, the file is considered already written
  192. and the rest are not called.
  193. These hooks are considered to pertain to the visited file.
  194. So this list is cleared if you change the visited file name.
  195. See also `write-contents-hooks'.
  196. Don't make this variable buffer-local; instead, use `local-write-file-hooks'.")
  197. ;;; However, in case someone does make it local...
  198. (put 'write-file-hooks 'permanent-local t)
  199.  
  200. (defvar local-write-file-hooks nil
  201.   "Just like `write-file-hooks', except intended for per-buffer use.
  202. The functions in this list are called before the ones in
  203. `write-file-hooks'.")
  204. (make-variable-buffer-local 'local-write-file-hooks)
  205. (put 'local-write-file-hooks 'permanent-local t)
  206.  
  207. (defvar write-contents-hooks nil
  208.   "List of functions to be called before writing out a buffer to a file.
  209. If one of them returns non-nil, the file is considered already written
  210. and the rest are not called.
  211. These hooks are considered to pertain to the buffer's contents,
  212. not to the particular visited file; thus, `set-visited-file-name' does
  213. not clear this variable, but changing the major mode does clear it.
  214. See also `write-file-hooks'.")
  215.  
  216. (defconst enable-local-variables t
  217.   "*Control use of local-variables lists in files you visit.
  218. The value can be t, nil or something else.
  219. A value of t means local-variables lists are obeyed;
  220. nil means they are ignored; anything else means query.
  221.  
  222. The command \\[normal-mode] always obeys local-variables lists
  223. and ignores this variable.")
  224.  
  225. (defconst enable-local-eval 'maybe
  226.   "*Control processing of the \"variable\" `eval' in a file's local variables.
  227. The value can be t, nil or something else.
  228. A value of t means obey `eval' variables;
  229. nil means ignore them; anything else means query.
  230.  
  231. The command \\[normal-mode] always obeys local-variables lists
  232. and ignores this variable.")
  233.  
  234. ;; Avoid losing in versions where CLASH_DETECTION is disabled.
  235. (or (fboundp 'lock-buffer)
  236.     (defalias 'lock-buffer 'ignore))
  237. (or (fboundp 'unlock-buffer)
  238.     (defalias 'unlock-buffer 'ignore))
  239.  
  240. ;; This hook function provides support for ange-ftp host name
  241. ;; completion.  It runs the usual ange-ftp hook, but only for
  242. ;; completion operations.  Having this here avoids the need
  243. ;; to load ange-ftp when it's not really in use.
  244. (defun ange-ftp-completion-hook-function (op &rest args)
  245.   (if (memq op '(file-name-completion file-name-all-completions))
  246.       (apply 'ange-ftp-hook-function op args)
  247.     (let ((inhibit-file-name-handlers
  248.        (cons 'ange-ftp-completion-hook-function
  249.          (and (eq inhibit-file-name-operation op)
  250.               inhibit-file-name-handlers)))
  251.       (inhibit-file-name-operation op))
  252.       (apply op args))))
  253.  
  254. (defun pwd ()
  255.   "Show the current default directory."
  256.   (interactive nil)
  257.   (message "Directory %s" default-directory))
  258.  
  259. (defvar cd-path nil
  260.   "Value of the CDPATH environment variable, as a list.
  261. Not actually set up until the first time you you use it.")
  262.  
  263. (defun parse-colon-path (cd-path)
  264.   "Explode a colon-separated list of paths into a string list."
  265.   (and cd-path
  266.        (let (cd-prefix cd-list (cd-start 0) cd-colon)
  267.      (setq cd-path (concat cd-path ":"))
  268.      (while (setq cd-colon (string-match ":" cd-path cd-start))
  269.        (setq cd-list
  270.          (nconc cd-list
  271.             (list (if (= cd-start cd-colon)
  272.                    nil
  273.                 (substitute-in-file-name
  274.                  (file-name-as-directory
  275.                   (substring cd-path cd-start cd-colon)))))))
  276.        (setq cd-start (+ cd-colon 1)))
  277.      cd-list)))
  278.  
  279. (defun cd-absolute (dir)
  280.   "Change current directory to given absolute file name DIR."
  281.   ;; Put the name into directory syntax now,
  282.   ;; because otherwise expand-file-name may give some bad results.
  283.   (if (not (eq system-type 'vax-vms))
  284.       (setq dir (file-name-as-directory dir)))
  285.   (setq dir (abbreviate-file-name (expand-file-name dir)))
  286.   (if (not (file-directory-p dir))
  287.       (error "%s is not a directory" dir)
  288.     (if (file-executable-p dir)
  289.     (setq default-directory dir)
  290.       (error "Cannot cd to %s:  Permission denied" dir))))
  291.  
  292. (defun cd (dir)
  293.   "Make DIR become the current buffer's default directory.
  294. If your environment includes a `CDPATH' variable, try each one of that
  295. colon-separated list of directories when resolving a relative directory name."
  296.   (interactive "FChange default directory: ")
  297.   (if (file-name-absolute-p dir)
  298.       (cd-absolute (expand-file-name dir))
  299.     (if (null cd-path)
  300.     (let ((trypath (parse-colon-path (getenv "CDPATH"))))
  301.       (setq cd-path (or trypath (list "./")))))
  302.     (if (not (catch 'found
  303.            (mapcar
  304.         (function (lambda (x)
  305.                 (let ((f (expand-file-name (concat x dir))))
  306.                   (if (file-directory-p f)
  307.                   (progn
  308.                     (cd-absolute f)
  309.                     (throw 'found t))))))
  310.         cd-path)
  311.            nil))
  312.     (error "No such directory found via CDPATH environment variable"))))
  313.  
  314. (defun load-file (file)
  315.   "Load the Lisp file named FILE."
  316.   (interactive "fLoad file: ")
  317.   (load (expand-file-name file) nil nil t))
  318.  
  319. (defun load-library (library)
  320.   "Load the library named LIBRARY.
  321. This is an interface to the function `load'."
  322.   (interactive "sLoad library: ")
  323.   (load library))
  324.  
  325. (defun file-local-copy (file &optional buffer)
  326.   "Copy the file FILE into a temporary file on this machine.
  327. Returns the name of the local copy, or nil, if FILE is directly
  328. accessible."
  329.   (let ((handler (find-file-name-handler file 'file-local-copy)))
  330.     (if handler
  331.     (funcall handler 'file-local-copy file)
  332.       nil)))
  333.  
  334. (defun file-truename (filename &optional counter prev-dirs)
  335.   "Return the truename of FILENAME, which should be absolute.
  336. The truename of a file name is found by chasing symbolic links
  337. both at the level of the file and at the level of the directories
  338. containing it, until no links are left at any level.
  339.  
  340. The arguments COUNTER and PREV-DIRS are used only in recursive calls.
  341. Do not specify them in other calls."
  342.   ;; COUNTER can be a cons cell whose car is the count of how many more links
  343.   ;; to chase before getting an error.
  344.   ;; PREV-DIRS can be a cons cell whose car is an alist
  345.   ;; of truenames we've just recently computed.
  346.   (if (or (string= filename "~")
  347.       (and (string= (substring filename 0 1) "~")
  348.            (string-match "~[^/]*" filename)))
  349.       (progn
  350.     (setq filename (expand-file-name filename))
  351.     (if (string= filename "")
  352.         (setq filename "/"))))
  353.   (or counter (setq counter (list 100)))
  354.   (let (done
  355.     ;; For speed, remove the ange-ftp completion handler from the list.
  356.     ;; We know it's not needed here.
  357.     ;; For even more speed, do this only on the outermost call.
  358.     (file-name-handler-alist
  359.      (if prev-dirs file-name-handler-alist
  360.        (let ((tem (copy-sequence file-name-handler-alist)))
  361.          (delq (rassq 'ange-ftp-completion-hook-function tem) tem)))))
  362.     (or prev-dirs (setq prev-dirs (list nil)))
  363.     ;; If this file directly leads to a link, process that iteratively
  364.     ;; so that we don't use lots of stack.
  365.     (while (not done)
  366.       (setcar counter (1- (car counter)))
  367.       (if (< (car counter) 0)
  368.       (error "Apparent cycle of symbolic links for %s" filename))
  369.       (let ((handler (find-file-name-handler filename 'file-truename)))
  370.     ;; For file name that has a special handler, call handler.
  371.     ;; This is so that ange-ftp can save time by doing a no-op.
  372.     (if handler
  373.         (setq filename (funcall handler 'file-truename filename)
  374.           done t)
  375.       (let ((dir (file-name-directory filename))
  376.         target dirfile)
  377.         ;; Get the truename of the directory.
  378.         (setq dirfile (directory-file-name dir))
  379.         ;; If these are equal, we have the (or a) root directory.
  380.         (or (string= dir dirfile)
  381.         ;; If this is the same dir we last got the truename for,
  382.         ;; save time--don't recalculate.
  383.         (if (assoc dir (car prev-dirs))
  384.             (setq dir (cdr (assoc dir (car prev-dirs))))
  385.           (let ((old dir)
  386.             (new (file-name-as-directory (file-truename dirfile counter prev-dirs))))
  387.             (setcar prev-dirs (cons (cons old new) (car prev-dirs)))
  388.             (setq dir new))))
  389.         (if (equal ".." (file-name-nondirectory filename))
  390.         (setq filename
  391.               (directory-file-name (file-name-directory (directory-file-name dir)))
  392.               done t)
  393.           (if (equal "." (file-name-nondirectory filename))
  394.           (setq filename (directory-file-name dir)
  395.             done t)
  396.         ;; Put it back on the file name.
  397.         (setq filename (concat dir (file-name-nondirectory filename)))
  398.         ;; Is the file name the name of a link?
  399.         (setq target (file-symlink-p filename))
  400.         (if target
  401.             ;; Yes => chase that link, then start all over
  402.             ;; since the link may point to a directory name that uses links.
  403.             ;; We can't safely use expand-file-name here
  404.             ;; since target might look like foo/../bar where foo
  405.             ;; is itself a link.  Instead, we handle . and .. above.
  406.             (setq filename
  407.               (if (file-name-absolute-p target)
  408.                   target
  409.                 (concat dir target))
  410.               done nil)
  411.           ;; No, we are done!
  412.           (setq done t))))))))
  413.     filename))
  414.  
  415. (defun file-chase-links (filename)
  416.   "Chase links in FILENAME until a name that is not a link.
  417. Does not examine containing directories for links,
  418. unlike `file-truename'."
  419.   (let (tem (count 100) (newname filename))
  420.     (while (setq tem (file-symlink-p newname))
  421.       (if (= count 0)
  422.       (error "Apparent cycle of symbolic links for %s" filename))
  423.       ;; In the context of a link, `//' doesn't mean what Emacs thinks.
  424.       (while (string-match "//+" tem)
  425.     (setq tem (concat (substring tem 0 (1+ (match-beginning 0)))
  426.               (substring tem (match-end 0)))))
  427.       ;; Handle `..' by hand, since it needs to work in the
  428.       ;; target of any directory symlink.
  429.       ;; This code is not quite complete; it does not handle
  430.       ;; embedded .. in some cases such as ./../foo and foo/bar/../../../lose.
  431.       (while (string-match "\\`\\.\\./" tem)
  432.     (setq tem (substring tem 3))
  433.     (setq newname (file-name-as-directory
  434.                ;; Do the .. by hand.
  435.                (directory-file-name
  436.             (file-name-directory
  437.              ;; Chase links in the default dir of the symlink.
  438.              (file-chase-links
  439.               (directory-file-name
  440.                (file-name-directory newname))))))))
  441.       (setq newname (expand-file-name tem (file-name-directory newname)))
  442.       (setq count (1- count)))
  443.     newname))
  444.  
  445. (defun switch-to-buffer-other-window (buffer)
  446.   "Select buffer BUFFER in another window."
  447.   (interactive "BSwitch to buffer in other window: ")
  448.   (let ((pop-up-windows t))
  449.     (pop-to-buffer buffer t)))
  450.  
  451. (defun switch-to-buffer-other-frame (buffer)
  452.   "Switch to buffer BUFFER in another frame."
  453.   (interactive "BSwitch to buffer in other frame: ")
  454.   (let ((pop-up-frames t))
  455.     (pop-to-buffer buffer t)
  456.     (raise-frame (window-frame (selected-window)))))
  457.  
  458. (defun find-file (filename)
  459.   "Edit file FILENAME.
  460. Switch to a buffer visiting file FILENAME,
  461. creating one if none already exists."
  462.   (interactive "FFind file: ")
  463.   (switch-to-buffer (find-file-noselect filename)))
  464.  
  465. (defun find-file-other-window (filename)
  466.   "Edit file FILENAME, in another window.
  467. May create a new window, or reuse an existing one.
  468. See the function `display-buffer'."
  469.   (interactive "FFind file in other window: ")
  470.   (switch-to-buffer-other-window (find-file-noselect filename)))
  471.  
  472. (defun find-file-other-frame (filename)
  473.   "Edit file FILENAME, in another frame.
  474. May create a new frame, or reuse an existing one.
  475. See the function `display-buffer'."
  476.   (interactive "FFind file in other frame: ")
  477.   (switch-to-buffer-other-frame (find-file-noselect filename)))
  478.  
  479. (defun find-file-read-only (filename)
  480.   "Edit file FILENAME but don't allow changes.
  481. Like \\[find-file] but marks buffer as read-only.
  482. Use \\[toggle-read-only] to permit editing."
  483.   (interactive "fFind file read-only: ")
  484.   (find-file filename)
  485.   (setq buffer-read-only t)
  486.   (current-buffer))
  487.  
  488. (defun find-file-read-only-other-window (filename)
  489.   "Edit file FILENAME in another window but don't allow changes.
  490. Like \\[find-file-other-window] but marks buffer as read-only.
  491. Use \\[toggle-read-only] to permit editing."
  492.   (interactive "fFind file read-only other window: ")
  493.   (find-file-other-window filename)
  494.   (setq buffer-read-only t)
  495.   (current-buffer))
  496.  
  497. (defun find-file-read-only-other-frame (filename)
  498.   "Edit file FILENAME in another frame but don't allow changes.
  499. Like \\[find-file-other-frame] but marks buffer as read-only.
  500. Use \\[toggle-read-only] to permit editing."
  501.   (interactive "fFind file read-only other frame: ")
  502.   (find-file-other-frame filename)
  503.   (setq buffer-read-only t)
  504.   (current-buffer))
  505.  
  506. (defun find-alternate-file (filename)
  507.   "Find file FILENAME, select its buffer, kill previous buffer.
  508. If the current buffer now contains an empty file that you just visited
  509. \(presumably by mistake), use this command to visit the file you really want."
  510.   (interactive
  511.    (let ((file buffer-file-name)
  512.      (file-name nil)
  513.      (file-dir nil))
  514.      (and file
  515.       (setq file-name (file-name-nondirectory file)
  516.         file-dir (file-name-directory file)))
  517.      (list (read-file-name
  518.         "Find alternate file: " file-dir nil nil file-name))))
  519.   (and (buffer-modified-p)
  520.        ;; (not buffer-read-only)
  521.        (not (yes-or-no-p (format "Buffer %s is modified; kill anyway? "
  522.                  (buffer-name))))
  523.        (error "Aborted"))
  524.   (let ((obuf (current-buffer))
  525.     (ofile buffer-file-name)
  526.     (onum buffer-file-number)
  527.     (otrue buffer-file-truename)
  528.     (oname (buffer-name)))
  529.     (rename-buffer " **lose**")
  530.     (setq buffer-file-name nil)
  531.     (setq buffer-file-number nil)
  532.     (setq buffer-file-truename nil)
  533.     (unwind-protect
  534.     (progn
  535.       (unlock-buffer)
  536.       (find-file filename))
  537.       (cond ((eq obuf (current-buffer))
  538.          (setq buffer-file-name ofile)
  539.          (setq buffer-file-number onum)
  540.          (setq buffer-file-truename otrue)
  541.          (lock-buffer)
  542.          (rename-buffer oname))))
  543.     (or (eq (current-buffer) obuf)
  544.     (kill-buffer obuf))))
  545.  
  546. (defun create-file-buffer (filename)
  547.   "Create a suitably named buffer for visiting FILENAME, and return it.
  548. FILENAME (sans directory) is used unchanged if that name is free;
  549. otherwise a string <2> or <3> or ... is appended to get an unused name."
  550.   (let ((lastname (file-name-nondirectory filename)))
  551.     (if (string= lastname "")
  552.     (setq lastname filename))
  553.     (generate-new-buffer lastname)))
  554.  
  555. (defun generate-new-buffer (name)
  556.   "Create and return a buffer with a name based on NAME.
  557. Choose the buffer's name using `generate-new-buffer-name'."
  558.   (get-buffer-create (generate-new-buffer-name name)))
  559.  
  560. (defconst automount-dir-prefix "^/tmp_mnt/"
  561.   "Regexp to match the automounter prefix in a directory name.")
  562.  
  563. (defvar abbreviated-home-dir nil
  564.   "The user's homedir abbreviated according to `directory-abbrev-list'.")
  565.  
  566. (defun abbreviate-file-name (filename)
  567.   "Return a version of FILENAME shortened using `directory-abbrev-alist'.
  568. This also substitutes \"~\" for the user's home directory.
  569. Type \\[describe-variable] directory-abbrev-alist RET for more information."
  570.   ;; Get rid of the prefixes added by the automounter.
  571.   (if (and (string-match automount-dir-prefix filename)
  572.        (file-exists-p (file-name-directory
  573.                (substring filename (1- (match-end 0))))))
  574.       (setq filename (substring filename (1- (match-end 0)))))
  575.   (let ((tail directory-abbrev-alist))
  576.     ;; If any elt of directory-abbrev-alist matches this name,
  577.     ;; abbreviate accordingly.
  578.     (while tail
  579.       (if (string-match (car (car tail)) filename)
  580.       (setq filename
  581.         (concat (cdr (car tail)) (substring filename (match-end 0)))))
  582.       (setq tail (cdr tail)))
  583.     ;; Compute and save the abbreviated homedir name.
  584.     ;; We defer computing this until the first time it's needed, to
  585.     ;; give time for directory-abbrev-alist to be set properly.
  586.     ;; We include a slash at the end, to avoid spurious matches
  587.     ;; such as `/usr/foobar' when the home dir is `/usr/foo'.
  588.     (or abbreviated-home-dir
  589.     (setq abbreviated-home-dir
  590.           (let ((abbreviated-home-dir "$foo"))
  591.         (concat "^" (abbreviate-file-name (expand-file-name "~"))
  592.             "\\(/\\|$\\)"))))
  593.                           
  594.     ;; If FILENAME starts with the abbreviated homedir,
  595.     ;; make it start with `~' instead.
  596.     (if (and (string-match abbreviated-home-dir filename)
  597.          ;; If the home dir is just /, don't change it.
  598.          (not (and (= (match-end 0) 1)
  599.                (= (aref filename 0) ?/)))
  600.          (not (and (eq system-type 'ms-dos)
  601.                (save-match-data
  602.              (string-match "^[a-zA-Z]:/$" filename)))))
  603.     (setq filename
  604.           (concat "~"
  605.               (substring filename (match-beginning 1) (match-end 1))
  606.               (substring filename (match-end 0)))))
  607.     filename))
  608.  
  609. (defvar find-file-not-true-dirname-list nil
  610.   "*List of logical names for which visiting shouldn't save the true dirname.
  611. On VMS, when you visit a file using a logical name that searches a path,
  612. you may or may not want the visited file name to record the specific
  613. directory where the file was found.  If you *do not* want that, add the logical
  614. name to this list as a string.")
  615.  
  616. (defun find-buffer-visiting (filename)
  617.   "Return the buffer visiting file FILENAME (a string).
  618. This is like `get-file-buffer', except that it checks for any buffer
  619. visiting the same file, possibly under a different name.
  620. If there is no such live buffer, return nil."
  621.   (let ((buf (get-file-buffer filename))
  622.     (truename (abbreviate-file-name (file-truename filename))))
  623.     (or buf
  624.     (let ((list (buffer-list)) found)
  625.       (while (and (not found) list)
  626.         (save-excursion
  627.           (set-buffer (car list))
  628.           (if (and buffer-file-name
  629.                (string= buffer-file-truename truename))
  630.           (setq found (car list))))
  631.         (setq list (cdr list)))
  632.       found)
  633.     (let ((number (nthcdr 10 (file-attributes truename)))
  634.           (list (buffer-list)) found)
  635.       (and number
  636.            (while (and (not found) list)
  637.          (save-excursion
  638.            (set-buffer (car list))
  639.            (if (and buffer-file-name
  640.                 (equal buffer-file-number number)
  641.                 ;; Verify this buffer's file number
  642.                 ;; still belongs to its file.
  643.                 (file-exists-p buffer-file-name)
  644.                 (equal (nthcdr 10 (file-attributes buffer-file-name))
  645.                    number))
  646.                (setq found (car list))))
  647.          (setq list (cdr list))))
  648.       found))))
  649.  
  650. (defun find-file-noselect (filename &optional nowarn)
  651.   "Read file FILENAME into a buffer and return the buffer.
  652. If a buffer exists visiting FILENAME, return that one, but
  653. verify that the file has not changed since visited or saved.
  654. The buffer is not selected, just returned to the caller."
  655.   (setq filename
  656.     (abbreviate-file-name
  657.      (expand-file-name filename)))
  658.   (if (file-directory-p filename)
  659.       (if find-file-run-dired
  660.       (dired-noselect filename)
  661.     (error "%s is a directory." filename))
  662.     (let* ((buf (get-file-buffer filename))
  663.        (truename (abbreviate-file-name (file-truename filename)))
  664.        (number (nthcdr 10 (file-attributes truename)))
  665.        ;; Find any buffer for a file which has same truename.
  666.        (other (and (not buf) (find-buffer-visiting filename)))
  667.        error)
  668.       ;; Let user know if there is a buffer with the same truename.
  669.       (if other
  670.       (progn
  671.         (or nowarn
  672.         (string-equal filename (buffer-file-name other))
  673.         (message "%s and %s are the same file"
  674.              filename (buffer-file-name other)))
  675.         ;; Optionally also find that buffer.
  676.         (if (or find-file-existing-other-name find-file-visit-truename)
  677.         (setq buf other))))
  678.       (if buf
  679.       (or nowarn
  680.           (verify-visited-file-modtime buf)
  681.           (cond ((not (file-exists-p filename))
  682.              (error "File %s no longer exists!" filename))
  683.             ((yes-or-no-p
  684.               (format
  685.                (if (buffer-modified-p buf)
  686.     "File %s changed on disk.  Discard your edits? "
  687.     "File %s changed on disk.  Reread from disk? ")
  688.                (file-name-nondirectory filename)))
  689.              (save-excursion
  690.                (set-buffer buf)
  691.                (revert-buffer t t)))))
  692.     (save-excursion
  693. ;;; The truename stuff makes this obsolete.
  694. ;;;      (let* ((link-name (car (file-attributes filename)))
  695. ;;;         (linked-buf (and (stringp link-name)
  696. ;;;                  (get-file-buffer link-name))))
  697. ;;;        (if (bufferp linked-buf)
  698. ;;;        (message "Symbolic link to file in buffer %s"
  699. ;;;             (buffer-name linked-buf))))
  700.       (setq buf (create-file-buffer filename))
  701.       (set-buffer buf)
  702.       (erase-buffer)
  703.       (condition-case ()
  704.           (insert-file-contents filename t)
  705.         (file-error
  706.          (setq error t)
  707.          ;; Run find-file-not-found-hooks until one returns non-nil.
  708.          (let ((hooks find-file-not-found-hooks))
  709.            (while (and hooks
  710.                (not (and (funcall (car hooks))
  711.                      ;; If a hook succeeded, clear error.
  712.                      (progn (setq error nil)
  713.                         ;; Also exit the loop.
  714.                         t))))
  715.          (setq hooks (cdr hooks))))))
  716.       ;; Find the file's truename, and maybe use that as visited name.
  717.       (setq buffer-file-truename truename)
  718.       (setq buffer-file-number number)
  719.       ;; On VMS, we may want to remember which directory in a search list
  720.       ;; the file was found in.
  721.       (and (eq system-type 'vax-vms)
  722.            (let (logical)
  723.          (if (string-match ":" (file-name-directory filename))
  724.              (setq logical (substring (file-name-directory filename)
  725.                           0 (match-beginning 0))))
  726.          (not (member logical find-file-not-true-dirname-list)))
  727.            (setq buffer-file-name buffer-file-truename))
  728.       (if find-file-visit-truename
  729.           (setq buffer-file-name
  730.             (setq filename
  731.               (expand-file-name buffer-file-truename))))
  732.       ;; Set buffer's default directory to that of the file.
  733.       (setq default-directory (file-name-directory filename))
  734.       ;; Turn off backup files for certain file names.  Since
  735.       ;; this is a permanent local, the major mode won't eliminate it.
  736.       (and (not (funcall backup-enable-predicate buffer-file-name))
  737.            (progn
  738.          (make-local-variable 'backup-inhibited)
  739.          (setq backup-inhibited t)))
  740.       (after-find-file error (not nowarn))))
  741.       buf)))
  742.  
  743. (defvar after-find-file-from-revert-buffer nil)
  744.  
  745. (defun after-find-file (&optional error warn noauto
  746.                   after-find-file-from-revert-buffer)
  747.   "Called after finding a file and by the default revert function.
  748. Sets buffer mode, parses local variables.
  749. Optional args ERROR, WARN, and NOAUTO: ERROR non-nil means there was an
  750. error in reading the file.  WARN non-nil means warn if there
  751. exists an auto-save file more recent than the visited file.
  752. NOAUTO means don't mess with auto-save mode.
  753. Fourth arg AFTER-FIND-FILE-FROM-REVERT-BUFFER non-nil
  754.  means this call was from `revert-buffer'.
  755. Finishes by calling the functions in `find-file-hooks'."
  756.   (setq buffer-read-only (not (file-writable-p buffer-file-name)))
  757.   (if noninteractive
  758.       nil
  759.     (let* (not-serious
  760.        (msg
  761.         (cond ((and error (file-attributes buffer-file-name))
  762.            (setq buffer-read-only t)
  763.            "File exists, but cannot be read.")
  764.           ((not buffer-read-only)
  765.            (if (and warn
  766.                 (file-newer-than-file-p (make-auto-save-file-name)
  767.                             buffer-file-name))
  768.                "Auto save file is newer; consider M-x recover-file"
  769.              (setq not-serious t)
  770.              (if error "(New file)" nil)))
  771.           ((not error)
  772.            (setq not-serious t)
  773.            "Note: file is write protected")
  774.           ((file-attributes (directory-file-name default-directory))
  775.            "File not found and directory write-protected")
  776.           ((file-exists-p (file-name-directory buffer-file-name))
  777.            (setq buffer-read-only nil))
  778.           (t
  779.            (setq buffer-read-only nil)
  780.            (if (file-exists-p (file-name-directory (directory-file-name (file-name-directory buffer-file-name))))
  781.                "Use M-x make-dir RET RET to create the directory"
  782.              "Use C-u M-x make-dir RET RET to create directory and its parents")))))
  783.       (if msg
  784.       (progn
  785.         (message msg)
  786.         (or not-serious (sit-for 1 nil t)))))
  787.     (if (and auto-save-default (not noauto))
  788.     (auto-save-mode t)))
  789.   (normal-mode t)
  790.   (mapcar 'funcall find-file-hooks))
  791.  
  792. (defun normal-mode (&optional find-file)
  793.   "Choose the major mode for this buffer automatically.
  794. Also sets up any specified local variables of the file.
  795. Uses the visited file name, the -*- line, and the local variables spec.
  796.  
  797. This function is called automatically from `find-file'.  In that case,
  798. we may set up specified local variables depending on the value of
  799. `enable-local-variables': if it is t, we do; if it is nil, we don't;
  800. otherwise, we query.  `enable-local-variables' is ignored if you
  801. run `normal-mode' explicitly."
  802.   (interactive)
  803.   (or find-file (funcall (or default-major-mode 'fundamental-mode)))
  804.   (condition-case err
  805.       (set-auto-mode)
  806.     (error (message "File mode specification error: %s"
  807.             (prin1-to-string err))))
  808.   (condition-case err
  809.       (let ((enable-local-variables (or (not find-file)
  810.                     enable-local-variables)))
  811.     (hack-local-variables))
  812.     (error (message "File local-variables error: %s"
  813.             (prin1-to-string err)))))
  814.  
  815. (defvar auto-mode-alist (mapcar 'purecopy
  816.                 '(("\\.text\\'" . text-mode)
  817.                   ("\\.c\\'" . c-mode)
  818.                   ("\\.h\\'" . c-mode)
  819.                   ("\\.tex\\'" . TeX-mode)
  820.                   ("\\.ltx\\'" . LaTeX-mode)
  821.                   ("\\.el\\'" . emacs-lisp-mode)
  822.                   ("\\.mm\\'" . nroff-mode)
  823.                   ("\\.me\\'" . nroff-mode)
  824.                   ("\\.ms\\'" . nroff-mode)
  825.                   ("\\.man\\'" . nroff-mode)
  826.                   ("\\.scm\\'" . scheme-mode)
  827.                   ("\\.l\\'" . lisp-mode)
  828.                   ("\\.lisp\\'" . lisp-mode)
  829.                   ("\\.f\\'" . fortran-mode)
  830.                   ("\\.for\\'" . fortran-mode)
  831.                   ("\\.p\\'" . pascal-mode)
  832.                   ("\\.pas\\'" . pascal-mode)
  833.                   ("\\.mss\\'" . scribe-mode)
  834.                   ("\\.pl\\'" . prolog-mode)
  835.                   ("\\.cc\\'" . c++-mode)
  836.                   ("\\.hh\\'" . c++-mode)
  837.                   ("\\.C\\'" . c++-mode)
  838.                   ("\\.H\\'" . c++-mode)
  839. ;;;                  ("\\.mk\\'" . makefile-mode)
  840. ;;;                  ("[Mm]akefile" . makefile-mode)
  841. ;;; Less common extensions come here
  842. ;;; so more common ones above are found faster.
  843.                   ("\\.texinfo\\'" . texinfo-mode)
  844.                   ("\\.texi\\'" . texinfo-mode)
  845.                   ("\\.s\\'" . asm-mode)
  846.                   ("ChangeLog\\'" . change-log-mode)
  847.                   ("change.log\\'" . change-log-mode)
  848.                   ("changelo\\'" . change-log-mode)
  849.                   ("ChangeLog.[0-9]+\\'" . change-log-mode)
  850.                   ("\\$CHANGE_LOG\\$\\.TXT" . change-log-mode)
  851. ;; The following should come after the ChangeLog pattern
  852. ;; for the sake of ChangeLog.1, etc.
  853.                   ("\\.[12345678]\\'" . nroff-mode)
  854.                   ("\\.TeX\\'" . TeX-mode)
  855.                   ("\\.sty\\'" . LaTeX-mode)
  856.                   ("\\.bbl\\'" . LaTeX-mode)
  857.                   ("\\.bib\\'" . bibtex-mode)
  858.                   ("\\.article\\'" . text-mode)
  859.                   ("\\.letter\\'" . text-mode)
  860.                   ("\\.tcl\\'" . tcl-mode)
  861.                   ("\\.lsp\\'" . lisp-mode)
  862.                   ("\\.awk\\'" . awk-mode)
  863.                   ("\\.prolog\\'" . prolog-mode)
  864.                   ("\\.tar\\'" . tar-mode)
  865.                   ;; Mailer puts message to be edited in
  866.                   ;; /tmp/Re.... or Message
  867.                   ("^/tmp/Re" . text-mode)
  868.                   ("/Message[0-9]*\\'" . text-mode)
  869.                   ;; some news reader is reported to use this
  870.                   ("^/tmp/fol/" . text-mode)
  871.                   ("\\.y\\'" . c-mode)
  872.                   ("\\.lex\\'" . c-mode)
  873.                   ("\\.oak\\'" . scheme-mode)
  874.                   ("\\.scm.[0-9]*\\'" . scheme-mode)
  875.                   ("\\.sgm\\'" . sgml-mode)
  876.                   ("\\.sgml\\'" . sgml-mode)
  877.                   ("\\.dtd\\'" . sgml-mode)
  878.                   ;; .emacs following a directory delimiter
  879.                   ;; in either Unix or VMS syntax.
  880.                   ("[]>:/]\\..*emacs\\'" . emacs-lisp-mode)
  881.                   ;; _emacs following a directory delimiter
  882.                   ;; in MsDos syntax
  883.                   ("[:/]_emacs\\'" . emacs-lisp-mode)
  884.                   ("\\.ml\\'" . lisp-mode)))
  885.   "\
  886. Alist of filename patterns vs corresponding major mode functions.
  887. Each element looks like (REGEXP . FUNCTION) or (REGEXP FUNCTION).
  888. Visiting a file whose name matches REGEXP causes FUNCTION to be called.
  889. If the element has the form (REGEXP FUNCTION), then after calling
  890. FUNCTION, we delete the suffix that matched REGEXP and search the list
  891. again for another match.")
  892.  
  893. (defconst interpreter-mode-alist
  894.   '(("perl" . perl-mode)
  895.     ("wish" . tcl-mode)
  896.     ("wishx" . tcl-mode)
  897.     ("tcl" . tcl-mode)
  898.     ("tclsh" . tcl-mode)
  899.     ("awk" . awk-mode)
  900.     ("gawk" . awk-mode)
  901.     ("scm" . scheme-mode))
  902.   "Alist mapping interpreter names to major modes.
  903. This alist applies to files whose first line starts with `#!'.
  904. Each element looks like (INTERPRETER . MODE).
  905. The car of each element is compared with
  906. the name of the interpreter specified in the first line.
  907. If it matches, mode MODE is selected.")
  908.  
  909. (defconst inhibit-first-line-modes-regexps '("\\.tar$")
  910.   "List of regexps; if one matches a file name, don't look for `-*-'.")
  911.  
  912. (defvar user-init-file
  913.   "" ; set by command-line
  914.   "File name including directory of user's initialization file.")
  915.  
  916. (defun set-auto-mode ()
  917.   "Select major mode appropriate for current buffer.
  918. This checks for a -*- mode tag in the buffer's text,
  919. compares the filename against the entries in `auto-mode-alist',
  920. or checks the interpreter that runs this file against
  921. `interpreter-mode-alist'.
  922.  
  923. It does not check for the `mode:' local variable in the
  924. Local Variables section of the file; for that, use `hack-local-variables'.
  925.  
  926. If `enable-local-variables' is nil, this function does not check for a
  927. -*- mode tag."
  928.   ;; Look for -*-MODENAME-*- or -*- ... mode: MODENAME; ... -*-
  929.   (let (beg end done)
  930.     (save-excursion
  931.       (goto-char (point-min))
  932.       (skip-chars-forward " \t\n")
  933.       (and enable-local-variables
  934.        ;; Don't look for -*- if this file name matches any
  935.        ;; of the regexps in inhibit-first-line-modes-regexps.
  936.        (let ((temp inhibit-first-line-modes-regexps))
  937.          (while (and temp
  938.              (not (string-match (car temp)
  939.                         buffer-file-name)))
  940.            (setq temp (cdr temp)))
  941.          (not temp))
  942.        (search-forward "-*-" (save-excursion
  943.                    ;; If the file begins with "#!"
  944.                    ;; (exec interpreter magic), look
  945.                    ;; for mode frobs in the first two
  946.                    ;; lines.  You cannot necessarily
  947.                    ;; put them in the first line of
  948.                    ;; such a file without screwing up
  949.                    ;; the interpreter invocation.
  950.                    (end-of-line (and (looking-at "^#!") 2))
  951.                    (point)) t)
  952.        (progn
  953.          (skip-chars-forward " \t")
  954.          (setq beg (point))
  955.          (search-forward "-*-"
  956.                  (save-excursion (end-of-line) (point))
  957.                  t))
  958.        (progn
  959.          (forward-char -3)
  960.          (skip-chars-backward " \t")
  961.          (setq end (point))
  962.          (goto-char beg)
  963.          (if (save-excursion (search-forward ":" end t))
  964.          ;; Find all specifications for the `mode:' variable
  965.          ;; and execute them left to right.
  966.          (while (let ((case-fold-search t))
  967.               (search-forward "mode:" end t))
  968.            (skip-chars-forward " \t")
  969.            (setq beg (point))
  970.            (if (search-forward ";" end t)
  971.                (forward-char -1)
  972.              (goto-char end))
  973.            (skip-chars-backward " \t")
  974.            (funcall (intern (concat (downcase (buffer-substring beg (point))) "-mode"))))
  975.            ;; Simple -*-MODE-*- case.
  976.            (funcall (intern (concat (downcase (buffer-substring beg end)) "-mode"))))
  977.          (setq done t)))
  978.       ;; If we didn't find a mode from a -*- line, try using the file name.
  979.       (if (and (not done) buffer-file-name)
  980.       (let ((name buffer-file-name)
  981.         (keep-going t))
  982.         ;; Remove backup-suffixes from file name.
  983.         (setq name (file-name-sans-versions name))
  984.         (while keep-going
  985.           (setq keep-going nil)
  986.           (let ((alist auto-mode-alist)
  987.             (mode nil))
  988.         ;; Find first matching alist entry.
  989.         (let ((case-fold-search (eq system-type 'vax-vms)))
  990.           (while (and (not mode) alist)
  991.             (if (string-match (car (car alist)) name)
  992.             (if (and (consp (cdr (car alist)))
  993.                  (nth 2 (car alist)))
  994.                 (progn
  995.                   (setq mode (car (cdr (car alist)))
  996.                     name (substring name 0 (match-beginning 0))
  997.                     keep-going t))
  998.               (setq mode (cdr (car alist))
  999.                 keep-going nil)))
  1000.             (setq alist (cdr alist))))
  1001.         (if mode
  1002.             (funcall mode)
  1003.           ;; If we can't deduce a mode from the file name,
  1004.           ;; look for an interpreter specified in the first line.
  1005.           (let ((interpreter
  1006.              (save-excursion
  1007.                (goto-char (point-min))
  1008.                (if (looking-at "#! *\\([^ \t\n]+\\)")
  1009.                    (buffer-substring (match-beginning 1)
  1010.                          (match-end 1))
  1011.                  "")))
  1012.             elt)
  1013.             ;; Map interpreter name to a mode.
  1014.             (setq elt (assoc (file-name-nondirectory interpreter)
  1015.                      interpreter-mode-alist))
  1016.             (if elt
  1017.             (funcall (cdr elt))))))))))))
  1018.  
  1019. (defun hack-local-variables-prop-line ()
  1020.   ;; Set local variables specified in the -*- line.
  1021.   ;; Ignore any specification for `mode:';
  1022.   ;; set-auto-mode should already have handled that.
  1023.   (save-excursion
  1024.     (goto-char (point-min))
  1025.     (let ((result nil)
  1026.       (end (save-excursion (end-of-line (and (looking-at "^#!") 2)) (point))))
  1027.       ;; Parse the -*- line into the `result' alist.
  1028.       (cond ((not (search-forward "-*-" end t))
  1029.          ;; doesn't have one.
  1030.          nil)
  1031.         ((looking-at "[ \t]*\\([^ \t\n\r:;]+\\)\\([ \t]*-\\*-\\)")
  1032.          ;; Simple form: "-*- MODENAME -*-".  Already handled.
  1033.          nil)
  1034.         (t
  1035.          ;; Hairy form: '-*-' [ <variable> ':' <value> ';' ]* '-*-'
  1036.          ;; (last ";" is optional).
  1037.          (save-excursion
  1038.            (if (search-forward "-*-" end t)
  1039.            (setq end (- (point) 3))
  1040.          (error "-*- not terminated before end of line")))
  1041.          (while (< (point) end)
  1042.            (or (looking-at "[ \t]*\\([^ \t\n:]+\\)[ \t]*:[ \t]*")
  1043.            (error "malformed -*- line"))
  1044.            (goto-char (match-end 0))
  1045.            (let ((key (intern (downcase (buffer-substring
  1046.                          (match-beginning 1)
  1047.                          (match-end 1)))))
  1048.              (val (save-restriction
  1049.                 (narrow-to-region (point) end)
  1050.                 (read (current-buffer)))))
  1051.          (or (eq key 'mode)
  1052.              (setq result (cons (cons key val) result)))
  1053.          (skip-chars-forward " \t;")))
  1054.          (setq result (nreverse result))))
  1055.       
  1056.       (if (and result
  1057.            (or (eq enable-local-variables t)
  1058.            (and enable-local-variables
  1059.             (save-window-excursion
  1060.               (condition-case nil
  1061.                   (switch-to-buffer (current-buffer))
  1062.                 (error
  1063.                  ;; If we fail to switch in the selected window,
  1064.                  ;; it is probably a minibuffer.
  1065.                  ;; So try another window.
  1066.                  (condition-case nil
  1067.                  (switch-to-buffer-other-window (current-buffer))
  1068.                    (error
  1069.                 (switch-to-buffer-other-frame (current-buffer))))))
  1070.               (y-or-n-p (format "Set local variables as specified in -*- line of %s? "
  1071.                         (file-name-nondirectory buffer-file-name)))))))
  1072.       (while result
  1073.         (hack-one-local-variable (car (car result)) (cdr (car result)))
  1074.         (setq result (cdr result)))))))
  1075.  
  1076. (defun hack-local-variables ()
  1077.   "Parse and put into effect this buffer's local variables spec."
  1078.   (hack-local-variables-prop-line)
  1079.   ;; Look for "Local variables:" line in last page.
  1080.   (save-excursion
  1081.     (goto-char (point-max))
  1082.     (search-backward "\n\^L" (max (- (point-max) 3000) (point-min)) 'move)
  1083.     (if (let ((case-fold-search t))
  1084.       (and (search-forward "Local Variables:" nil t)
  1085.            (or (eq enable-local-variables t)
  1086.            (and enable-local-variables
  1087.             (save-window-excursion
  1088.               (switch-to-buffer (current-buffer))
  1089.               (save-excursion
  1090.                 (beginning-of-line)
  1091.                 (set-window-start (selected-window) (point)))
  1092.               (y-or-n-p (format "Set local variables as specified at end of %s? "
  1093.                          (if buffer-file-name
  1094.                          (file-name-nondirectory 
  1095.                           buffer-file-name)
  1096.                            (concat "buffer "
  1097.                                (buffer-name))))))))))
  1098.     (let ((continue t)
  1099.           prefix prefixlen suffix beg
  1100.           (enable-local-eval enable-local-eval))
  1101.       ;; The prefix is what comes before "local variables:" in its line.
  1102.       ;; The suffix is what comes after "local variables:" in its line.
  1103.       (skip-chars-forward " \t")
  1104.       (or (eolp)
  1105.           (setq suffix (buffer-substring (point)
  1106.                          (progn (end-of-line) (point)))))
  1107.       (goto-char (match-beginning 0))
  1108.       (or (bolp)
  1109.           (setq prefix
  1110.             (buffer-substring (point)
  1111.                       (progn (beginning-of-line) (point)))))
  1112.  
  1113.       (if prefix (setq prefixlen (length prefix)
  1114.                prefix (regexp-quote prefix)))
  1115.       (if suffix (setq suffix (concat (regexp-quote suffix) "$")))
  1116.       (while continue
  1117.         ;; Look at next local variable spec.
  1118.         (if selective-display (re-search-forward "[\n\C-m]")
  1119.           (forward-line 1))
  1120.         ;; Skip the prefix, if any.
  1121.         (if prefix
  1122.         (if (looking-at prefix)
  1123.             (forward-char prefixlen)
  1124.           (error "Local variables entry is missing the prefix")))
  1125.         ;; Find the variable name; strip whitespace.
  1126.         (skip-chars-forward " \t")
  1127.         (setq beg (point))
  1128.         (skip-chars-forward "^:\n")
  1129.         (if (eolp) (error "Missing colon in local variables entry"))
  1130.         (skip-chars-backward " \t")
  1131.         (let* ((str (buffer-substring beg (point)))
  1132.            (var (read str))
  1133.           val)
  1134.           ;; Setting variable named "end" means end of list.
  1135.           (if (string-equal (downcase str) "end")
  1136.           (setq continue nil)
  1137.         ;; Otherwise read the variable value.
  1138.         (skip-chars-forward "^:")
  1139.         (forward-char 1)
  1140.         (setq val (read (current-buffer)))
  1141.         (skip-chars-backward "\n")
  1142.         (skip-chars-forward " \t")
  1143.         (or (if suffix (looking-at suffix) (eolp))
  1144.             (error "Local variables entry is terminated incorrectly"))
  1145.         ;; Set the variable.  "Variables" mode and eval are funny.
  1146.         (hack-one-local-variable var val))))))))
  1147.  
  1148. (defconst ignored-local-variables
  1149.   '(enable-local-eval)
  1150.   "Variables to be ignored in a file's local variable spec.")
  1151.  
  1152. ;; Get confirmation before setting these variables as locals in a file.
  1153. (put 'debugger 'risky-local-variable t)
  1154. (put 'enable-local-eval 'risky-local-variable t)
  1155. (put 'eval 'risky-local-variable t)
  1156. (put 'file-name-handler-alist 'risky-local-variable t)
  1157. (put 'minor-mode-map-alist 'risky-local-variable t)
  1158. (put 'after-load-alist 'risky-local-variable t)
  1159. (put 'buffer-file-name 'risky-local-variable t)
  1160. (put 'buffer-auto-save-file-name 'risky-local-variable t)
  1161. (put 'buffer-file-truename 'risky-local-variable t)
  1162. (put 'exec-path 'risky-local-variable t)
  1163. (put 'load-path 'risky-local-variable t)
  1164. (put 'exec-directory 'risky-local-variable t)
  1165. (put 'process-environment 'risky-local-variable t)
  1166. ;; Don't wait for outline.el to be loaded, for the sake of outline-minor-mode.
  1167. (put 'outline-level 'risky-local-variable t)
  1168. (put 'rmail-output-file-alist 'risky-local-variable t)
  1169.  
  1170. (defun hack-one-local-variable-quotep (exp)
  1171.   (and (consp exp) (eq (car exp) 'quote) (consp (cdr exp))))
  1172.  
  1173. ;; "Set" one variable in a local variables spec.
  1174. ;; A few variable names are treated specially.
  1175. (defun hack-one-local-variable (var val)
  1176.   (cond ((eq var 'mode)
  1177.      (funcall (intern (concat (downcase (symbol-name val))
  1178.                   "-mode"))))
  1179.     ((memq var ignored-local-variables)
  1180.      nil)
  1181.     ;; "Setting" eval means either eval it or do nothing.
  1182.     ;; Likewise for setting hook variables.
  1183.     ((or (get var 'risky-local-variable)
  1184.          (string-match "-hooks?$\\|-functions?$\\|-forms?$\\|-program$\\|-command$"
  1185.                (symbol-name var)))
  1186.      ;; Permit evaling a put of a harmless property
  1187.      ;; if the args do nothing tricky.
  1188.      (if (or (and (eq var 'eval)
  1189.               (consp val)
  1190.               (eq (car val) 'put)
  1191.               (hack-one-local-variable-quotep (nth 1 val))
  1192.               (hack-one-local-variable-quotep (nth 2 val))
  1193.               ;; Only allow safe values of lisp-indent-hook;
  1194.               ;; not functions.
  1195.               (or (numberp (nth 3 val))
  1196.               (equal (nth 3 val) ''defun))
  1197.               (memq (nth 1 (nth 2 val))
  1198.                 '(lisp-indent-hook)))
  1199.          ;; Permit eval if not root and user says ok.
  1200.          (and (not (zerop (user-uid)))
  1201.               (or (eq enable-local-eval t)
  1202.               (and enable-local-eval
  1203.                    (save-window-excursion
  1204.                  (switch-to-buffer (current-buffer))
  1205.                  (save-excursion
  1206.                    (beginning-of-line)
  1207.                    (set-window-start (selected-window) (point)))
  1208.                  (setq enable-local-eval
  1209.                        (y-or-n-p (format "Process `eval' or hook local variables in file %s? "
  1210.                              (file-name-nondirectory buffer-file-name)))))))))
  1211.          (if (eq var 'eval)
  1212.          (save-excursion (eval val))
  1213.            (make-local-variable var)
  1214.            (set var val))
  1215.        (message "Ignoring `eval:' in file's local variables")))
  1216.     ;; Ordinary variable, really set it.
  1217.     (t (make-local-variable var)
  1218.        (set var val))))
  1219.  
  1220.  
  1221. (defun set-visited-file-name (filename)
  1222.   "Change name of file visited in current buffer to FILENAME.
  1223. The next time the buffer is saved it will go in the newly specified file.
  1224. nil or empty string as argument means make buffer not be visiting any file.
  1225. Remember to delete the initial contents of the minibuffer
  1226. if you wish to pass an empty string as the argument."
  1227.   (interactive "FSet visited file name: ")
  1228.   (let (truename)
  1229.     (if filename
  1230.     (setq filename
  1231.           (if (string-equal filename "")
  1232.           nil
  1233.         (expand-file-name filename))))
  1234.     (if filename
  1235.     (progn
  1236.       (setq truename (file-truename filename))
  1237.       (if find-file-visit-truename
  1238.           ;; Do not use the abbreviated filename, because
  1239.           ;; write-region will reset it to the expanded filename
  1240.           (setq filename truename))))
  1241.     (or (equal filename buffer-file-name)
  1242.     (progn
  1243.       (and filename (lock-buffer filename))
  1244.       (unlock-buffer)))
  1245.     (setq buffer-file-name filename)
  1246.     (if filename            ; make buffer name reflect filename.
  1247.     (let ((new-name (file-name-nondirectory buffer-file-name)))
  1248.       (if (string= new-name "")
  1249.           (error "Empty file name"))
  1250.       (if (eq system-type 'vax-vms)
  1251.           (setq new-name (downcase new-name)))
  1252.       (setq default-directory (file-name-directory buffer-file-name))
  1253.       (or (string= new-name (buffer-name))
  1254.           (rename-buffer new-name t))))
  1255.     (setq buffer-backed-up nil)
  1256.     (clear-visited-file-modtime)
  1257.     (if truename
  1258.     (setq buffer-file-truename (abbreviate-file-name truename)))
  1259.     (setq buffer-file-number
  1260.       (if filename
  1261.           (nth 10 (file-attributes buffer-file-name))
  1262.           nil)))
  1263.   ;; write-file-hooks is normally used for things like ftp-find-file
  1264.   ;; that visit things that are not local files as if they were files.
  1265.   ;; Changing to visit an ordinary local file instead should flush the hook.
  1266.   (kill-local-variable 'write-file-hooks)
  1267.   (kill-local-variable 'local-write-file-hooks)
  1268.   (kill-local-variable 'revert-buffer-function)
  1269.   (kill-local-variable 'backup-inhibited)
  1270.   ;; If buffer was read-only because of version control,
  1271.   ;; that reason is gone now, so make it writable.
  1272.   (if vc-mode
  1273.       (setq buffer-read-only nil))
  1274.   (kill-local-variable 'vc-mode)
  1275.   ;; Turn off backup files for certain file names.
  1276.   ;; Since this is a permanent local, the major mode won't eliminate it.
  1277.   (and (not (funcall backup-enable-predicate buffer-file-name))
  1278.        (progn
  1279.      (make-local-variable 'backup-inhibited)
  1280.      (setq backup-inhibited t)))
  1281.   (let ((oauto buffer-auto-save-file-name))
  1282.     ;; If auto-save was not already on, turn it on if appropriate.
  1283.     (if (not buffer-auto-save-file-name)
  1284.     (and buffer-file-name auto-save-default
  1285.          (auto-save-mode t))
  1286.       ;; If auto save is on, start using a new name.
  1287.       ;; We deliberately don't rename or delete the old auto save
  1288.       ;; for the old visited file name.  This is because perhaps
  1289.       ;; the user wants to save the new state and then compare with the
  1290.       ;; previous state from the auto save file.
  1291.       (setq buffer-auto-save-file-name
  1292.         (make-auto-save-file-name)))
  1293.     ;; Rename the old auto save file if any.
  1294.     (and oauto buffer-auto-save-file-name
  1295.      (file-exists-p oauto)
  1296.      (rename-file oauto buffer-auto-save-file-name t)))
  1297.   (if buffer-file-name
  1298.       (set-buffer-modified-p t)))
  1299.  
  1300. (defun write-file (filename)
  1301.   "Write current buffer into file FILENAME.
  1302. Makes buffer visit that file, and marks it not modified.
  1303. If the buffer is already visiting a file, you can specify
  1304. a directory name as FILENAME, to write a file of the same
  1305. old name in that directory."
  1306. ;;  (interactive "FWrite file: ")
  1307.   (interactive
  1308.    (list (if buffer-file-name
  1309.          (read-file-name "Write file: "
  1310.                  nil nil nil nil)
  1311.        (read-file-name "Write file: "
  1312.                    (cdr (assq 'default-directory
  1313.                       (buffer-local-variables)))
  1314.                    nil nil (buffer-name)))))
  1315.   (or (null filename) (string-equal filename "")
  1316.       (progn
  1317.     ;; If arg is just a directory,
  1318.     ;; use same file name, but in that directory.
  1319.     (if (and (file-directory-p filename) buffer-file-name)
  1320.         (setq filename (concat (file-name-as-directory filename)
  1321.                    (file-name-nondirectory buffer-file-name))))
  1322.     (set-visited-file-name filename)))
  1323.   (set-buffer-modified-p t)
  1324.   (save-buffer))
  1325.  
  1326. (defun backup-buffer ()
  1327.   "Make a backup of the disk file visited by the current buffer, if appropriate.
  1328. This is normally done before saving the buffer the first time.
  1329. If the value is non-nil, it is the result of `file-modes' on the original
  1330. file; this means that the caller, after saving the buffer, should change
  1331. the modes of the new file to agree with the old modes."
  1332.   (if (and make-backup-files (not backup-inhibited)
  1333.        (not buffer-backed-up)
  1334.        (file-exists-p buffer-file-name)
  1335.        (memq (aref (elt (file-attributes buffer-file-name) 8) 0)
  1336.          '(?- ?l)))
  1337.       (let ((real-file-name buffer-file-name)
  1338.         backup-info backupname targets setmodes)
  1339.     ;; If specified name is a symbolic link, chase it to the target.
  1340.     ;; Thus we make the backups in the directory where the real file is.
  1341.     (setq real-file-name (file-chase-links real-file-name))
  1342.     (setq backup-info (find-backup-file-name real-file-name)
  1343.           backupname (car backup-info)
  1344.           targets (cdr backup-info))
  1345. ;;;     (if (file-directory-p buffer-file-name)
  1346. ;;;         (error "Cannot save buffer in directory %s" buffer-file-name))
  1347.         (condition-case ()
  1348.         (let ((delete-old-versions
  1349.            ;; If have old versions to maybe delete,
  1350.            ;; ask the user to confirm now, before doing anything.
  1351.            ;; But don't actually delete til later.
  1352.            (and targets
  1353.             (or (eq delete-old-versions t) (eq delete-old-versions nil))
  1354.             (or delete-old-versions
  1355.                 (y-or-n-p (format "Delete excess backup versions of %s? "
  1356.                           real-file-name))))))
  1357.           ;; Actually write the back up file.
  1358.           (condition-case ()
  1359.           (if (or file-precious-flag
  1360. ;              (file-symlink-p buffer-file-name)
  1361.               backup-by-copying
  1362.               (and backup-by-copying-when-linked
  1363.                    (> (file-nlinks real-file-name) 1))
  1364.               (and backup-by-copying-when-mismatch
  1365.                    (let ((attr (file-attributes real-file-name)))
  1366.                  (or (nth 9 attr)
  1367.                      (/= (nth 2 attr) (user-uid))))))
  1368.               (condition-case ()
  1369.               (copy-file real-file-name backupname t t)
  1370.             (file-error
  1371.              ;; If copying fails because file BACKUPNAME
  1372.              ;; is not writable, delete that file and try again.
  1373.              (if (and (file-exists-p backupname)
  1374.                   (not (file-writable-p backupname)))
  1375.                  (delete-file backupname))
  1376.              (copy-file real-file-name backupname t t)))
  1377.             ;; rename-file should delete old backup.
  1378.             (rename-file real-file-name backupname t)
  1379.             (setq setmodes (file-modes backupname)))
  1380.         (file-error
  1381.          ;; If trouble writing the backup, write it in ~.
  1382.          (setq backupname (expand-file-name "~/%backup%~"))
  1383.          (message "Cannot write backup file; backing up in ~/%%backup%%~")
  1384.          (sleep-for 1)
  1385.          (condition-case ()
  1386.              (copy-file real-file-name backupname t t)
  1387.            (file-error
  1388.             ;; If copying fails because file BACKUPNAME
  1389.             ;; is not writable, delete that file and try again.
  1390.             (if (and (file-exists-p backupname)
  1391.                  (not (file-writable-p backupname)))
  1392.             (delete-file backupname))
  1393.             (copy-file real-file-name backupname t t)))))
  1394.           (setq buffer-backed-up t)
  1395.           ;; Now delete the old versions, if desired.
  1396.           (if delete-old-versions
  1397.           (while targets
  1398.             (condition-case ()
  1399.             (delete-file (car targets))
  1400.               (file-error nil))
  1401.             (setq targets (cdr targets))))
  1402.           setmodes)
  1403.     (file-error nil)))))
  1404.  
  1405. (defun file-name-sans-versions (name &optional keep-backup-version)
  1406.   "Return FILENAME sans backup versions or strings.
  1407. This is a separate procedure so your site-init or startup file can
  1408. redefine it.
  1409. If the optional argument KEEP-BACKUP-VERSION is non-nil,
  1410. we do not remove backup version numbers, only true file version numbers."
  1411.   (let ((handler (find-file-name-handler name 'file-name-sans-versions)))
  1412.     (if handler
  1413.     (funcall handler 'file-name-sans-versions name keep-backup-version)
  1414.       (substring name 0
  1415.          (if (eq system-type 'vax-vms)
  1416.              ;; VMS version number is (a) semicolon, optional
  1417.              ;; sign, zero or more digits or (b) period, option
  1418.              ;; sign, zero or more digits, provided this is the
  1419.              ;; second period encountered outside of the
  1420.              ;; device/directory part of the file name.
  1421.              (or (string-match ";[-+]?[0-9]*\\'" name)
  1422.              (if (string-match "\\.[^]>:]*\\(\\.[-+]?[0-9]*\\)\\'"
  1423.                        name)
  1424.                  (match-beginning 1))
  1425.              (length name))
  1426.            (if keep-backup-version
  1427.                (length name)
  1428.              (or (string-match "\\.~[0-9]+~\\'" name)
  1429.              (string-match "~\\'" name)
  1430.              (length name))))))))
  1431.  
  1432. (defun make-backup-file-name (file)
  1433.   "Create the non-numeric backup file name for FILE.
  1434. This is a separate function so you can redefine it for customization."
  1435.   (if (eq system-type 'ms-dos)
  1436.       (let ((fn (file-name-nondirectory file)))
  1437.     (concat (file-name-directory file)
  1438.         (if (string-match "\\([^.]*\\)\\(\\..*\\)?" fn)
  1439.             (substring fn 0 (match-end 1)))
  1440.         ".bak"))
  1441.     (concat file "~")))
  1442.  
  1443. (defun backup-file-name-p (file)
  1444.   "Return non-nil if FILE is a backup file name (numeric or not).
  1445. This is a separate function so you can redefine it for customization.
  1446. You may need to redefine `file-name-sans-versions' as well."
  1447.   (if (eq system-type 'ms-dos)
  1448.       (string-match "\\.bak$" file)
  1449.     (string-match "~$" file)))
  1450.  
  1451. ;; This is used in various files.
  1452. ;; The usage of bv-length is not very clean,
  1453. ;; but I can't see a good alternative,
  1454. ;; so as of now I am leaving it alone.
  1455. (defun backup-extract-version (fn)
  1456.   "Given the name of a numeric backup file, return the backup number.
  1457. Uses the free variable `bv-length', whose value should be
  1458. the index in the name where the version number begins."
  1459.   (if (and (string-match "[0-9]+~$" fn bv-length)
  1460.        (= (match-beginning 0) bv-length))
  1461.       (string-to-int (substring fn bv-length -1))
  1462.       0))
  1463.  
  1464. ;; I believe there is no need to alter this behavior for VMS;
  1465. ;; since backup files are not made on VMS, it should not get called.
  1466. (defun find-backup-file-name (fn)
  1467.   "Find a file name for a backup file, and suggestions for deletions.
  1468. Value is a list whose car is the name for the backup file
  1469.  and whose cdr is a list of old versions to consider deleting now."
  1470.   (if (eq version-control 'never)
  1471.       (list (make-backup-file-name fn))
  1472.     (let* ((base-versions (concat (file-name-nondirectory fn) ".~"))
  1473.        (bv-length (length base-versions))
  1474.        possibilities
  1475.        (versions nil)
  1476.        (high-water-mark 0)
  1477.        (deserve-versions-p nil)
  1478.        (number-to-delete 0))
  1479.       (condition-case ()
  1480.       (setq possibilities (file-name-all-completions
  1481.                    base-versions
  1482.                    (file-name-directory fn))
  1483.         versions (sort (mapcar
  1484.                 (function backup-extract-version)
  1485.                 possibilities)
  1486.                    '<)
  1487.         high-water-mark (apply 'max 0 versions)
  1488.         deserve-versions-p (or version-control
  1489.                        (> high-water-mark 0))
  1490.         number-to-delete (- (length versions)
  1491.                     kept-old-versions kept-new-versions -1))
  1492.     (file-error
  1493.      (setq possibilities nil)))
  1494.       (if (not deserve-versions-p)
  1495.       (list (make-backup-file-name fn))
  1496.     (cons (concat fn ".~" (int-to-string (1+ high-water-mark)) "~")
  1497.           (if (and (> number-to-delete 0)
  1498.                        ;; Delete nothing if there is overflow
  1499.                ;; in the number of versions to keep.
  1500.                (>= (+ kept-new-versions kept-old-versions -1) 0))
  1501.           (mapcar (function (lambda (n)
  1502.                       (concat fn ".~" (int-to-string n) "~")))
  1503.               (let ((v (nthcdr kept-old-versions versions)))
  1504.                 (rplacd (nthcdr (1- number-to-delete) v) ())
  1505.                 v))))))))
  1506.  
  1507. (defun file-nlinks (filename)
  1508.   "Return number of names file FILENAME has."
  1509.   (car (cdr (file-attributes filename))))
  1510.  
  1511. (defun file-relative-name (filename &optional directory)
  1512.   "Convert FILENAME to be relative to DIRECTORY (default: default-directory)."
  1513.   (setq filename (expand-file-name filename)
  1514.     directory (file-name-as-directory (expand-file-name
  1515.                        (or directory default-directory))))
  1516.   (let ((ancestor ""))
  1517.     (while (not (string-match (concat "^" (regexp-quote directory)) filename))
  1518.       (setq directory (file-name-directory (substring directory 0 -1))
  1519.         ancestor (concat "../" ancestor)))
  1520.     (concat ancestor (substring filename (match-end 0)))))
  1521.  
  1522. (defun save-buffer (&optional args)
  1523.   "Save current buffer in visited file if modified.  Versions described below.
  1524. By default, makes the previous version into a backup file
  1525.  if previously requested or if this is the first save.
  1526. With 1 or 3 \\[universal-argument]'s, marks this version
  1527.  to become a backup when the next save is done.
  1528. With 2 or 3 \\[universal-argument]'s,
  1529.  unconditionally makes the previous version into a backup file.
  1530. With argument of 0, never makes the previous version into a backup file.
  1531.  
  1532. If a file's name is FOO, the names of its numbered backup versions are
  1533.  FOO.~i~ for various integers i.  A non-numbered backup file is called FOO~.
  1534. Numeric backups (rather than FOO~) will be made if value of
  1535.  `version-control' is not the atom `never' and either there are already
  1536.  numeric versions of the file being backed up, or `version-control' is
  1537.  non-nil.
  1538. We don't want excessive versions piling up, so there are variables
  1539.  `kept-old-versions', which tells Emacs how many oldest versions to keep,
  1540.  and `kept-new-versions', which tells how many newest versions to keep.
  1541.  Defaults are 2 old versions and 2 new.
  1542. `dired-kept-versions' controls dired's clean-directory (.) command.
  1543. If `delete-old-versions' is nil, system will query user
  1544.  before trimming versions.  Otherwise it does it silently."
  1545.   (interactive "p")
  1546.   (let ((modp (buffer-modified-p))
  1547.     (large (> (buffer-size) 50000))
  1548.     (make-backup-files (or (and make-backup-files (not (eq args 0)))
  1549.                    (memq args '(16 64)))))
  1550.     (and modp (memq args '(16 64)) (setq buffer-backed-up nil))
  1551.     (if (and modp large) (message "Saving file %s..." (buffer-file-name)))
  1552.     (basic-save-buffer)
  1553.     (and modp (memq args '(4 64)) (setq buffer-backed-up nil))))
  1554.  
  1555. (defun delete-auto-save-file-if-necessary (&optional force)
  1556.   "Delete auto-save file for current buffer if `delete-auto-save-files' is t.
  1557. Normally delete only if the file was written by this Emacs since
  1558. the last real save, but optional arg FORCE non-nil means delete anyway."
  1559.   (and buffer-auto-save-file-name delete-auto-save-files
  1560.        (not (string= buffer-file-name buffer-auto-save-file-name))
  1561.        (or force (recent-auto-save-p))
  1562.        (progn
  1563.      (condition-case ()
  1564.          (delete-file buffer-auto-save-file-name)
  1565.        (file-error nil))
  1566.      (set-buffer-auto-saved))))
  1567.  
  1568. (defun basic-save-buffer ()
  1569.   "Save the current buffer in its visited file, if it has been modified."
  1570.   (interactive)
  1571.   (if (buffer-modified-p)
  1572.       (let ((recent-save (recent-auto-save-p))
  1573.         setmodes tempsetmodes)
  1574.     ;; On VMS, rename file and buffer to get rid of version number.
  1575.     (if (and (eq system-type 'vax-vms)
  1576.          (not (string= buffer-file-name
  1577.                    (file-name-sans-versions buffer-file-name))))
  1578.         (let (buffer-new-name)
  1579.           ;; Strip VMS version number before save.
  1580.           (setq buffer-file-name
  1581.             (file-name-sans-versions buffer-file-name))
  1582.           ;; Construct a (unique) buffer name to correspond.
  1583.           (let ((buf (create-file-buffer (downcase buffer-file-name))))
  1584.         (setq buffer-new-name (buffer-name buf))
  1585.         (kill-buffer buf))
  1586.           (rename-buffer buffer-new-name)))
  1587.     ;; If buffer has no file name, ask user for one.
  1588.     (or buffer-file-name
  1589.         (set-visited-file-name
  1590.          (expand-file-name (read-file-name "File to save in: ") nil)))
  1591.     (or (verify-visited-file-modtime (current-buffer))
  1592.         (not (file-exists-p buffer-file-name))
  1593.         (yes-or-no-p
  1594.          (format "%s has changed since visited or saved.  Save anyway? "
  1595.              (file-name-nondirectory buffer-file-name)))
  1596.         (error "Save not confirmed"))
  1597.     (save-restriction
  1598.       (widen)
  1599.       (and (> (point-max) 1)
  1600.            (/= (char-after (1- (point-max))) ?\n)
  1601.            (not (and (eq selective-display t)
  1602.              (= (char-after (1- (point-max))) ?\r)))
  1603.            (or (eq require-final-newline t)
  1604.            (and require-final-newline
  1605.             (y-or-n-p
  1606.              (format "Buffer %s does not end in newline.  Add one? "
  1607.                  (buffer-name)))))
  1608.            (save-excursion
  1609.          (goto-char (point-max))
  1610.          (insert ?\n)))
  1611.       (let ((hooks (append write-contents-hooks local-write-file-hooks
  1612.                    write-file-hooks))
  1613.         (done nil))
  1614.         (while (and hooks
  1615.             (not (setq done (funcall (car hooks)))))
  1616.           (setq hooks (cdr hooks)))
  1617.         ;; If a hook returned t, file is already "written".
  1618.         (cond ((not done)
  1619.            (setq setmodes (basic-save-buffer-1)))))
  1620.       (setq buffer-file-number (nth 10 (file-attributes buffer-file-name)))
  1621.       (if setmodes
  1622.           (condition-case ()
  1623.           (set-file-modes buffer-file-name setmodes)
  1624.         (error nil))))
  1625.     ;; If the auto-save file was recent before this command,
  1626.     ;; delete it now.
  1627.     (delete-auto-save-file-if-necessary recent-save)
  1628.     (run-hooks 'after-save-hook))
  1629.     (message "(No changes need to be saved)")))
  1630.  
  1631. ;; This does the "real job" of writing a buffer into its visited file
  1632. ;; and making a backup file.  This is what is normally done
  1633. ;; but inhibited if one of write-file-hooks returns non-nil.
  1634. ;; It returns a value to store in setmodes.
  1635. (defun basic-save-buffer-1 ()
  1636.   (let (tempsetmodes setmodes)
  1637.     (if (not (file-writable-p buffer-file-name))
  1638.     (let ((dir (file-name-directory buffer-file-name)))
  1639.       (if (not (file-directory-p dir))
  1640.           (error "%s is not a directory" dir)
  1641.         (if (not (file-exists-p buffer-file-name))
  1642.         (error "Directory %s write-protected" dir)
  1643.           (if (yes-or-no-p
  1644.            (format "File %s is write-protected; try to save anyway? "
  1645.                (file-name-nondirectory
  1646.                 buffer-file-name)))
  1647.           (setq tempsetmodes t)
  1648.         (error "Attempt to save to a file which you aren't allowed to write"))))))
  1649.     (or buffer-backed-up
  1650.     (setq setmodes (backup-buffer)))
  1651.     (let ((dir (file-name-directory buffer-file-name))) 
  1652.       (if (and file-precious-flag
  1653.            (file-writable-p dir))
  1654.       ;; If file is precious, write temp name, then rename it.
  1655.       ;; This requires write access to the containing dir,
  1656.       ;; which is why we don't try it if we don't have that access.
  1657.       (let ((realname buffer-file-name)
  1658.         tempname temp nogood i succeed)
  1659.         (setq i 0)
  1660.         (setq nogood t)
  1661.         ;; Find the temporary name to write under.
  1662.         (while nogood
  1663.           (setq tempname (format "%s#tmp#%d" dir i))
  1664.           (setq nogood (file-exists-p tempname))
  1665.           (setq i (1+ i)))
  1666.         (unwind-protect
  1667.         (progn (clear-visited-file-modtime)
  1668.                (write-region (point-min) (point-max)
  1669.                      tempname nil realname)
  1670.                (setq succeed t))
  1671.           ;; If writing the temp file fails,
  1672.           ;; delete the temp file.
  1673.           (or succeed (delete-file tempname)))
  1674.         ;; Since we have created an entirely new file
  1675.         ;; and renamed it, make sure it gets the
  1676.         ;; right permission bits set.
  1677.         (setq setmodes (file-modes buffer-file-name))
  1678.         ;; We succeeded in writing the temp file,
  1679.         ;; so rename it.
  1680.         (rename-file tempname buffer-file-name t))
  1681.     ;; If file not writable, see if we can make it writable
  1682.     ;; temporarily while we write it.
  1683.     ;; But no need to do so if we have just backed it up
  1684.     ;; (setmodes is set) because that says we're superseding.
  1685.     (cond ((and tempsetmodes (not setmodes))
  1686.            ;; Change the mode back, after writing.
  1687.            (setq setmodes (file-modes buffer-file-name))
  1688.            (set-file-modes buffer-file-name 511)))
  1689.     (write-region (point-min) (point-max)
  1690.               buffer-file-name nil t)))
  1691.     setmodes))
  1692.  
  1693. (defun save-some-buffers (&optional arg exiting)
  1694.   "Save some modified file-visiting buffers.  Asks user about each one.
  1695. Optional argument (the prefix) non-nil means save all with no questions.
  1696. Optional second argument EXITING means ask about certain non-file buffers
  1697.  as well as about file buffers."
  1698.   (interactive "P")
  1699.   (save-window-excursion
  1700.     (let ((files-done
  1701.        (map-y-or-n-p
  1702.         (function
  1703.          (lambda (buffer)
  1704.            (and (buffer-modified-p buffer)
  1705.             (or
  1706.              (buffer-file-name buffer)
  1707.              (and exiting
  1708.               (progn
  1709.                 (set-buffer buffer)
  1710.                 (and buffer-offer-save (> (buffer-size) 0)))))
  1711.             (if arg
  1712.             t
  1713.               (if (buffer-file-name buffer)
  1714.               (format "Save file %s? "
  1715.                   (buffer-file-name buffer))
  1716.             (format "Save buffer %s? "
  1717.                 (buffer-name buffer)))))))
  1718.         (function
  1719.          (lambda (buffer)
  1720.            (set-buffer buffer)
  1721.            (save-buffer)))
  1722.         (buffer-list)
  1723.         '("buffer" "buffers" "save")
  1724.         (list (list ?\C-r (lambda (buf)
  1725.                 (view-buffer buf)
  1726.                 (setq view-exit-action
  1727.                       '(lambda (ignore)
  1728.                      (exit-recursive-edit)))
  1729.                 (recursive-edit)
  1730.                 ;; Return nil to ask about BUF again.
  1731.                 nil)
  1732.             "display the current buffer"))))
  1733.       (abbrevs-done
  1734.        (and save-abbrevs abbrevs-changed
  1735.         (progn
  1736.           (if (or arg
  1737.               (y-or-n-p (format "Save abbrevs in %s? " abbrev-file-name)))
  1738.               (write-abbrev-file nil))
  1739.           ;; Don't keep bothering user if he says no.
  1740.           (setq abbrevs-changed nil)
  1741.           t))))
  1742.       (or (> files-done 0) abbrevs-done
  1743.       (message "(No files need saving)")))))
  1744.  
  1745. (defun not-modified (&optional arg)
  1746.   "Mark current buffer as unmodified, not needing to be saved.
  1747. With prefix arg, mark buffer as modified, so \\[save-buffer] will save."
  1748.   (interactive "P")
  1749.   (message (if arg "Modification-flag set"
  1750.            "Modification-flag cleared"))
  1751.   (set-buffer-modified-p arg))
  1752.  
  1753. (defun toggle-read-only (&optional arg)
  1754.   "Change whether this buffer is visiting its file read-only.
  1755. With arg, set read-only iff arg is positive."
  1756.   (interactive "P")
  1757.   (setq buffer-read-only
  1758.     (if (null arg)
  1759.             (not buffer-read-only)
  1760.             (> (prefix-numeric-value arg) 0)))
  1761.   ;; Force mode-line redisplay
  1762.   (set-buffer-modified-p (buffer-modified-p)))
  1763.  
  1764. (defun insert-file (filename)
  1765.   "Insert contents of file FILENAME into buffer after point.
  1766. Set mark after the inserted text.
  1767.  
  1768. This function is meant for the user to run interactively.
  1769. Don't call it from programs!  Use `insert-file-contents' instead.
  1770. \(Its calling sequence is different; see its documentation)."
  1771.   (interactive "*fInsert file: ")
  1772.   (if (file-directory-p filename)
  1773.       (signal 'file-error (list "Opening input file" "file is a directory"
  1774.                 filename)))
  1775.   (let ((tem (insert-file-contents filename)))
  1776.     (push-mark (+ (point) (car (cdr tem))))))
  1777.  
  1778. (defun append-to-file (start end filename)
  1779.   "Append the contents of the region to the end of file FILENAME.
  1780. When called from a function, expects three arguments,
  1781. START, END and FILENAME.  START and END are buffer positions
  1782. saying what text to write."
  1783.   (interactive "r\nFAppend to file: ")
  1784.   (write-region start end filename t))
  1785.  
  1786. (defun file-newest-backup (filename)
  1787.   "Return most recent backup file for FILENAME or nil if no backups exist."
  1788.   (let* ((filename (expand-file-name filename))
  1789.      (file (file-name-nondirectory filename))
  1790.      (dir  (file-name-directory    filename))
  1791.      (comp (file-name-all-completions file dir))
  1792.      newest)
  1793.     (while comp
  1794.       (setq file (concat dir (car comp))
  1795.         comp (cdr comp))
  1796.       (if (and (backup-file-name-p file)
  1797.            (or (null newest) (file-newer-than-file-p file newest)))
  1798.       (setq newest file)))
  1799.     newest))
  1800.  
  1801. (defun rename-uniquely ()
  1802.   "Rename current buffer to a similar name not already taken.
  1803. This function is useful for creating multiple shell process buffers
  1804. or multiple mail buffers, etc."
  1805.   (interactive)
  1806.   (let* ((new-buf (generate-new-buffer (buffer-name)))
  1807.      (name (buffer-name new-buf)))
  1808.     (kill-buffer new-buf)
  1809.     (rename-buffer name)
  1810.     (set-buffer-modified-p (buffer-modified-p)))) ; force mode line update
  1811.  
  1812. (defun make-directory (dir &optional parents)
  1813.   "Create the directory DIR and any nonexistent parent dirs.
  1814. Interactively, the default choice of directory to create
  1815. is the current default directory for file names.
  1816. That is useful when you have visited a file in a nonexistint directory.
  1817.  
  1818. Noninteractively, the second (optional) argument PARENTS says whether
  1819. to create parent directories if they don't exist."
  1820.   (interactive
  1821.    (list (read-file-name "Make directory: " default-directory default-directory
  1822.              nil nil)
  1823.      t))
  1824.   (let ((handler (find-file-name-handler dir 'make-directory)))
  1825.     (if handler
  1826.     (funcall handler 'make-directory dir parents)
  1827.       (if (not parents)
  1828.       (make-directory-internal dir)
  1829.     (let ((dir (directory-file-name (expand-file-name dir)))
  1830.           create-list)
  1831.       (while (not (file-exists-p dir))
  1832.         (setq create-list (cons dir create-list)        
  1833.           dir (directory-file-name (file-name-directory dir))))
  1834.       (while create-list
  1835.         (make-directory-internal (car create-list))
  1836.         (setq create-list (cdr create-list))))))))
  1837.  
  1838. (put 'revert-buffer-function 'permanent-local t)
  1839. (defvar revert-buffer-function nil
  1840.   "Function to use to revert this buffer, or nil to do the default.
  1841. The function receives two arguments IGNORE-AUTO and NOCONFIRM,
  1842. which are the arguments that `revert-buffer' received.")
  1843.  
  1844. (put 'revert-buffer-insert-file-contents-function 'permanent-local t)
  1845. (defvar revert-buffer-insert-file-contents-function nil
  1846.   "Function to use to insert contents when reverting this buffer.
  1847. Gets two args, first the nominal file name to use,
  1848. and second, t if reading the auto-save file.")
  1849.  
  1850. (defun revert-buffer (&optional ignore-auto noconfirm)
  1851.   "Replace the buffer text with the text of the visited file on disk.
  1852. This undoes all changes since the file was visited or saved.
  1853. With a prefix argument, offer to revert from latest auto-save file, if
  1854. that is more recent than the visited file.
  1855.  
  1856. When called from lisp, The first argument is IGNORE-AUTO; only offer
  1857. to revert from the auto-save file when this is nil.  Note that the
  1858. sense of this argument is the reverse of the prefix argument, for the
  1859. sake of backward compatibility.  IGNORE-AUTO is optional, defaulting
  1860. to nil.
  1861.  
  1862. Optional second argument NOCONFIRM means don't ask for confirmation at
  1863. all.
  1864.  
  1865. If the value of `revert-buffer-function' is non-nil, it is called to
  1866. do the work.
  1867.  
  1868. The default revert function runs the hook `before-revert-hook' at the
  1869. beginning and `after-revert-hook' at the end."
  1870.   ;; I admit it's odd to reverse the sense of the prefix argument, but
  1871.   ;; there is a lot of code out there which assumes that the first
  1872.   ;; argument should be t to avoid consulting the auto-save file, and
  1873.   ;; there's no straightforward way to encourage authors to notice a
  1874.   ;; reversal of the argument sense.  So I'm just changing the user
  1875.   ;; interface, but leaving the programmatic interface the same.
  1876.   (interactive (list (not prefix-arg)))
  1877.   (if revert-buffer-function
  1878.       (funcall revert-buffer-function ignore-auto noconfirm)
  1879.     (let* ((opoint (point))
  1880.        (auto-save-p (and (not ignore-auto)
  1881.                  (recent-auto-save-p)
  1882.                  buffer-auto-save-file-name
  1883.                  (file-readable-p buffer-auto-save-file-name)
  1884.                  (y-or-n-p
  1885.    "Buffer has been auto-saved recently.  Revert from auto-save file? ")))
  1886.        (file-name (if auto-save-p
  1887.               buffer-auto-save-file-name
  1888.             buffer-file-name)))
  1889.       (cond ((null file-name)
  1890.          (error "Buffer does not seem to be associated with any file"))
  1891.         ((or noconfirm
  1892.          (yes-or-no-p (format "Revert buffer from file %s? "
  1893.                       file-name)))
  1894.          (run-hooks 'before-revert-hook)
  1895.          ;; If file was backed up but has changed since,
  1896.          ;; we shd make another backup.
  1897.          (and (not auto-save-p)
  1898.           (not (verify-visited-file-modtime (current-buffer)))
  1899.           (setq buffer-backed-up nil))
  1900.          ;; Get rid of all undo records for this buffer.
  1901.          (or (eq buffer-undo-list t)
  1902.          (setq buffer-undo-list nil))
  1903.          (let ((buffer-read-only nil)
  1904.            ;; Don't make undo records for the reversion.
  1905.            (buffer-undo-list t))
  1906.            (if revert-buffer-insert-file-contents-function
  1907.            (funcall revert-buffer-insert-file-contents-function
  1908.                 file-name auto-save-p)
  1909.          (if (not (file-exists-p file-name))
  1910.              (error "File %s no longer exists!" file-name))
  1911.          ;; Bind buffer-file-name to nil
  1912.          ;; so that we don't try to lock the file.
  1913.          (let ((buffer-file-name nil))
  1914.            (or auto-save-p
  1915.                (unlock-buffer)))
  1916.          (widen)
  1917.          (insert-file-contents file-name (not auto-save-p)
  1918.                        nil nil t)))
  1919.          (goto-char (min opoint (point-max)))
  1920.          (after-find-file nil nil t t)
  1921.          (run-hooks 'after-revert-hook)
  1922.          t)))))
  1923.  
  1924. (defun recover-file (file)
  1925.   "Visit file FILE, but get contents from its last auto-save file."
  1926.   (interactive
  1927.    (let ((prompt-file buffer-file-name)
  1928.      (file-name nil)
  1929.      (file-dir nil))
  1930.      (and prompt-file
  1931.       (setq file-name (file-name-nondirectory prompt-file)
  1932.         file-dir (file-name-directory prompt-file)))
  1933.      (list (read-file-name "Recover file: "
  1934.                    file-dir nil nil file-name))))
  1935.   (setq file (expand-file-name file))
  1936.   (if (auto-save-file-name-p (file-name-nondirectory file))
  1937.       (error "%s is an auto-save file" file))
  1938.   (let ((file-name (let ((buffer-file-name file))
  1939.              (make-auto-save-file-name))))
  1940.     (cond ((not (file-newer-than-file-p file-name file))
  1941.        (error "Auto-save file %s not current" file-name))
  1942.       ((save-window-excursion
  1943.          (if (not (eq system-type 'vax-vms))
  1944.          (with-output-to-temp-buffer "*Directory*"
  1945.            (buffer-disable-undo standard-output)
  1946.            (call-process "ls" nil standard-output nil
  1947.                  (if (file-symlink-p file) "-lL" "-l")
  1948.                  file file-name)))
  1949.          (yes-or-no-p (format "Recover auto save file %s? " file-name)))
  1950.        (switch-to-buffer (find-file-noselect file t))
  1951.        (let ((buffer-read-only nil))
  1952.          (erase-buffer)
  1953.          (insert-file-contents file-name nil))
  1954.        (after-find-file nil nil t))
  1955.       (t (error "Recover-file cancelled.")))))
  1956.  
  1957. (defun kill-some-buffers ()
  1958.   "For each buffer, ask whether to kill it."
  1959.   (interactive)
  1960.   (let ((list (buffer-list)))
  1961.     (while list
  1962.       (let* ((buffer (car list))
  1963.          (name (buffer-name buffer)))
  1964.     (and (not (string-equal name ""))
  1965.          (/= (aref name 0) ? )
  1966.          (yes-or-no-p
  1967.           (format "Buffer %s %s.  Kill? "
  1968.               name
  1969.               (if (buffer-modified-p buffer)
  1970.               "HAS BEEN EDITED" "is unmodified")))
  1971.          (kill-buffer buffer)))
  1972.       (setq list (cdr list)))))
  1973.  
  1974. (defun auto-save-mode (arg)
  1975.   "Toggle auto-saving of contents of current buffer.
  1976. With prefix argument ARG, turn auto-saving on if positive, else off."
  1977.   (interactive "P")
  1978.   (setq buffer-auto-save-file-name
  1979.         (and (if (null arg)
  1980.          (or (not buffer-auto-save-file-name)
  1981.              ;; If autosave is off because buffer has shrunk,
  1982.              ;; then toggling should turn it on.
  1983.              (< buffer-saved-size 0))
  1984.            (or (eq arg t) (listp arg) (and (integerp arg) (> arg 0))))
  1985.          (if (and buffer-file-name auto-save-visited-file-name
  1986.               (not buffer-read-only))
  1987.          buffer-file-name
  1988.            (make-auto-save-file-name))))
  1989.   ;; If -1 was stored here, to temporarily turn off saving,
  1990.   ;; turn it back on.
  1991.   (and (< buffer-saved-size 0)
  1992.        (setq buffer-saved-size 0))
  1993.   (if (interactive-p)
  1994.       (message "Auto-save %s (in this buffer)"
  1995.            (if buffer-auto-save-file-name "on" "off")))
  1996.   buffer-auto-save-file-name)
  1997.  
  1998. (defun rename-auto-save-file ()
  1999.   "Adjust current buffer's auto save file name for current conditions.
  2000. Also rename any existing auto save file, if it was made in this session."
  2001.   (let ((osave buffer-auto-save-file-name))
  2002.     (setq buffer-auto-save-file-name
  2003.       (make-auto-save-file-name))
  2004.     (if (and osave buffer-auto-save-file-name
  2005.          (not (string= buffer-auto-save-file-name buffer-file-name))
  2006.          (not (string= buffer-auto-save-file-name osave))
  2007.          (file-exists-p osave)
  2008.          (recent-auto-save-p))
  2009.     (rename-file osave buffer-auto-save-file-name t))))
  2010.  
  2011. (defun make-auto-save-file-name ()
  2012.   "Return file name to use for auto-saves of current buffer.
  2013. Does not consider `auto-save-visited-file-name' as that variable is checked
  2014. before calling this function.  You can redefine this for customization.
  2015. See also `auto-save-file-name-p'."
  2016.   (if buffer-file-name
  2017.       (concat (file-name-directory buffer-file-name)
  2018.           "#"
  2019.           (file-name-nondirectory buffer-file-name)
  2020.           "#")
  2021.  
  2022.     ;; Deal with buffers that don't have any associated files.  (Mail
  2023.     ;; mode tends to create a good number of these.)
  2024.  
  2025.     (let ((buffer-name (buffer-name))
  2026.       (limit 0))
  2027.       ;; Use technique from Sebastian Kremer's auto-save
  2028.       ;; package to turn slashes into \\!.  This ensures that
  2029.       ;; the auto-save buffer name is unique.
  2030.  
  2031.       (while (string-match "[/\\]" buffer-name limit)
  2032.     (setq buffer-name (concat (substring buffer-name 0 (match-beginning 0))
  2033.             (if (string= (substring buffer-name
  2034.                         (match-beginning 0)
  2035.                         (match-end 0))
  2036.                      "/")
  2037.                 "\\!"
  2038.               "\\\\")
  2039.             (substring buffer-name (match-end 0))))
  2040.     (setq limit (1+ (match-end 0))))
  2041.  
  2042.       (expand-file-name (format "#%s#%s#" buffer-name (make-temp-name ""))))))
  2043.  
  2044. (defun auto-save-file-name-p (filename)
  2045.   "Return non-nil if FILENAME can be yielded by `make-auto-save-file-name'.
  2046. FILENAME should lack slashes.  You can redefine this for customization."
  2047.   (string-match "^#.*#$" filename))
  2048.  
  2049. (defconst list-directory-brief-switches
  2050.   (if (eq system-type 'vax-vms) "" "-CF")
  2051.   "*Switches for list-directory to pass to `ls' for brief listing,")
  2052.  
  2053. (defconst list-directory-verbose-switches
  2054.   (if (eq system-type 'vax-vms)
  2055.       "/PROTECTION/SIZE/DATE/OWNER/WIDTH=(OWNER:10)"
  2056.     "-l")
  2057.   "*Switches for list-directory to pass to `ls' for verbose listing,")
  2058.  
  2059. (defun list-directory (dirname &optional verbose)
  2060.   "Display a list of files in or matching DIRNAME, a la `ls'.
  2061. DIRNAME is globbed by the shell if necessary.
  2062. Prefix arg (second arg if noninteractive) means supply -l switch to `ls'.
  2063. Actions controlled by variables `list-directory-brief-switches'
  2064. and `list-directory-verbose-switches'."
  2065.   (interactive (let ((pfx current-prefix-arg))
  2066.          (list (read-file-name (if pfx "List directory (verbose): "
  2067.                      "List directory (brief): ")
  2068.                        nil default-directory nil)
  2069.                pfx)))
  2070.   (let ((switches (if verbose list-directory-verbose-switches
  2071.             list-directory-brief-switches)))
  2072.     (or dirname (setq dirname default-directory))
  2073.     (setq dirname (expand-file-name dirname))
  2074.     (with-output-to-temp-buffer "*Directory*"
  2075.       (buffer-disable-undo standard-output)
  2076.       (princ "Directory ")
  2077.       (princ dirname)
  2078.       (terpri)
  2079.       (save-excursion
  2080.     (set-buffer "*Directory*")
  2081.     (let ((wildcard (not (file-directory-p dirname))))
  2082.       (insert-directory dirname switches wildcard (not wildcard)))))))
  2083.  
  2084. (defvar insert-directory-program "ls"
  2085.   "Absolute or relative name of the `ls' program used by `insert-directory'.")
  2086.  
  2087. ;; insert-directory
  2088. ;; - must insert _exactly_one_line_ describing FILE if WILDCARD and
  2089. ;;   FULL-DIRECTORY-P is nil.
  2090. ;;   The single line of output must display FILE's name as it was
  2091. ;;   given, namely, an absolute path name.
  2092. ;; - must insert exactly one line for each file if WILDCARD or
  2093. ;;   FULL-DIRECTORY-P is t, plus one optional "total" line
  2094. ;;   before the file lines, plus optional text after the file lines.
  2095. ;;   Lines are delimited by "\n", so filenames containing "\n" are not
  2096. ;;   allowed.
  2097. ;;   File lines should display the basename.
  2098. ;; - must be consistent with
  2099. ;;   - functions dired-move-to-filename, (these two define what a file line is)
  2100. ;;            dired-move-to-end-of-filename,
  2101. ;;         dired-between-files, (shortcut for (not (dired-move-to-filename)))
  2102. ;;            dired-insert-headerline
  2103. ;;            dired-after-subdir-garbage (defines what a "total" line is)
  2104. ;;   - variable dired-subdir-regexp
  2105. (defun insert-directory (file switches &optional wildcard full-directory-p)
  2106.   "Insert directory listing for FILE, formatted according to SWITCHES.
  2107. Leaves point after the inserted text.
  2108. SWITCHES may be a string of options, or a list of strings.
  2109. Optional third arg WILDCARD means treat FILE as shell wildcard.
  2110. Optional fourth arg FULL-DIRECTORY-P means file is a directory and
  2111. switches do not contain `d', so that a full listing is expected.
  2112.  
  2113. This works by running a directory listing program
  2114. whose name is in the variable `insert-directory-program'.
  2115. If WILDCARD, it also runs the shell specified by `shell-file-name'."
  2116.   ;; We need the directory in order to find the right handler.
  2117.   (let ((handler (find-file-name-handler (expand-file-name file)
  2118.                      'insert-directory)))
  2119.     (if handler
  2120.     (funcall handler 'insert-directory file switches
  2121.          wildcard full-directory-p)
  2122.       (if (eq system-type 'vax-vms)
  2123.       (vms-read-directory file switches (current-buffer))
  2124.     (if wildcard
  2125.         ;; Run ls in the directory of the file pattern we asked for.
  2126.         (let ((default-directory
  2127.             (if (file-name-absolute-p file)
  2128.             (file-name-directory file)
  2129.               (file-name-directory (expand-file-name file))))
  2130.           (pattern (file-name-nondirectory file))
  2131.           (beg 0))
  2132.           ;; Quote some characters that have special meanings in shells;
  2133.           ;; but don't quote the wildcards--we want them to be special.
  2134.           ;; We also currently don't quote the quoting characters
  2135.           ;; in case people want to use them explicitly to quote
  2136.           ;; wildcard characters.
  2137.           (while (string-match "[ \t\n;<>&|()#$]" pattern beg)
  2138.         (setq pattern
  2139.               (concat (substring pattern 0 (match-beginning 0))
  2140.                   "\\"
  2141.                   (substring pattern (match-beginning 0)))
  2142.               beg (1+ (match-end 0))))
  2143.           (call-process shell-file-name nil t nil
  2144.                 "-c" (concat insert-directory-program
  2145.                      " -d "
  2146.                      (if (stringp switches)
  2147.                          switches
  2148.                        (mapconcat 'identity switches " "))
  2149.                      " "
  2150.                      pattern)))
  2151.       ;; SunOS 4.1.3, SVr4 and others need the "." to list the
  2152.       ;; directory if FILE is a symbolic link.
  2153.       (apply 'call-process
  2154.          insert-directory-program nil t nil
  2155.          (let (list)
  2156.            (if (listp switches)
  2157.                (setq list switches)
  2158.              (if (not (equal switches ""))
  2159.              (progn
  2160.                ;; Split the switches at any spaces
  2161.                ;; so we can pass separate options as separate args.
  2162.                (while (string-match " " switches)
  2163.                  (setq list (cons (substring switches 0 (match-beginning 0))
  2164.                           list)
  2165.                    switches (substring switches (match-end 0))))
  2166.                (setq list (cons switches list)))))
  2167.            (append list
  2168.                (list
  2169.                 (if full-directory-p
  2170.                 (concat (file-name-as-directory file) ".")
  2171.                   file))))))))))
  2172.  
  2173. (defvar kill-emacs-query-functions nil
  2174.   "Functions to call with no arguments to query about killing Emacs.
  2175. If any of these functions returns nil, killing Emacs is cancelled.")
  2176.  
  2177. (defun save-buffers-kill-emacs (&optional arg)
  2178.   "Offer to save each buffer, then kill this Emacs process.
  2179. With prefix arg, silently save all file-visiting buffers, then kill."
  2180.   (interactive "P")
  2181.   (save-some-buffers arg t)
  2182.   (and (or (not (memq t (mapcar (function
  2183.                   (lambda (buf) (and (buffer-file-name buf)
  2184.                              (buffer-modified-p buf))))
  2185.                 (buffer-list))))
  2186.        (yes-or-no-p "Modified buffers exist; exit anyway? "))
  2187.        (or (not (fboundp 'process-list))
  2188.        ;; process-list is not defined on VMS.
  2189.        (let ((processes (process-list))
  2190.          active)
  2191.          (while processes
  2192.            (and (memq (process-status (car processes)) '(run stop open))
  2193.             (let ((val (process-kill-without-query (car processes))))
  2194.               (process-kill-without-query (car processes) val)
  2195.               val)
  2196.             (setq active t))
  2197.            (setq processes (cdr processes)))
  2198.          (or (not active)
  2199.          (yes-or-no-p "Active processes exist; kill them and exit anyway? "))))
  2200.        ;; Query the user for other things, perhaps.
  2201.        (let ((functions kill-emacs-query-functions)
  2202.          (yes t))
  2203.      (while (and functions yes)
  2204.        (setq yes (and yes (funcall (car functions))))
  2205.        (setq functions (cdr functions)))
  2206.      yes)
  2207.        (kill-emacs)))
  2208.  
  2209. (define-key ctl-x-map "\C-f" 'find-file)
  2210. (define-key ctl-x-map "\C-q" 'toggle-read-only)
  2211. (define-key ctl-x-map "\C-r" 'find-file-read-only)
  2212. (define-key ctl-x-map "\C-v" 'find-alternate-file)
  2213. (define-key ctl-x-map "\C-s" 'save-buffer)
  2214. (define-key ctl-x-map "s" 'save-some-buffers)
  2215. (define-key ctl-x-map "\C-w" 'write-file)
  2216. (define-key ctl-x-map "i" 'insert-file)
  2217. (define-key esc-map "~" 'not-modified)
  2218. (define-key ctl-x-map "\C-d" 'list-directory)
  2219. (define-key ctl-x-map "\C-c" 'save-buffers-kill-emacs)
  2220.  
  2221. (define-key ctl-x-4-map "f" 'find-file-other-window)
  2222. (define-key ctl-x-4-map "r" 'find-file-read-only-other-window)
  2223. (define-key ctl-x-4-map "\C-f" 'find-file-other-window)
  2224. (define-key ctl-x-4-map "b" 'switch-to-buffer-other-window)
  2225. (define-key ctl-x-4-map "\C-o" 'display-buffer)
  2226.  
  2227. (define-key ctl-x-5-map "b" 'switch-to-buffer-other-frame)
  2228. (define-key ctl-x-5-map "f" 'find-file-other-frame)
  2229. (define-key ctl-x-5-map "\C-f" 'find-file-other-frame)
  2230. (define-key ctl-x-5-map "r" 'find-file-read-only-other-frame)
  2231.  
  2232. ;;; files.el ends here
  2233.